Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

2D Tower Defense Game : Place Towers and Moving Towers on Grids Map

Discussion in '2D' started by busyxiang, Jun 7, 2016.

  1. busyxiang

    busyxiang

    Joined:
    Jun 7, 2016
    Posts:
    6
    Hi guys, I'm currently working on a 2D Tower Defense game where the towers are place on a set of grids and player can move the towers from grid to grid. However, when I place a tower on a grid and the tower itself have a circle collider that act as the detection range and it is overlapping the boxcollider of the grids around the tower, those grids cannot detect the mouse and makes it impossible to plant tower on it. I'm, trying to do a drag and drop for the tower movement as well but the problem is the towers wont snap onto the grid.

     
  2. capnjake

    capnjake

    Joined:
    Nov 12, 2013
    Posts:
    53
    I recently implemented a grid using a simple technique involving Mathf.Round(). I essentially just take the values of the mousePosition and save a rounded version of that to a Vector2.

    Code (csharp):
    1. Vector2 roundedPosition = new Vector2(Mathf.Round(mousePosition.x), Mathf.Round(mousePosition.y));
    Then when placing a tower just place the tower at the roundedPosition rather than the actual mousePosition.

    edit: I also use raycasts to check mousePosition so you may need to modify the position numbers a little depending on how you getting where the mouse is.
     
    Last edited: Jun 7, 2016
    JoeStrout likes this.
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Yeah, what @capnjake said. You don't need to be using colliders to detect clicks in a grid-based game... just do the simple math to figure out what grid square was clicked.