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 grid movement and collisions

Discussion in '2D' started by Squitz, Oct 4, 2019.

  1. Squitz

    Squitz

    Joined:
    Sep 29, 2019
    Posts:
    4
    Hy
    Im making a puzzle game where the object need to move in a grid wich i made.
    The problem is that I can't seem to find a tutorial on how to make it so they don't overlap or are stopped by walls. The colliders don't work because of the grid based movement.
    Their don't seem to be any tutorials or videos explaining on how to do it.

    this is my code so far.

    public class move : MonoBehaviour
    {
    public Rigidbody2D rb;
    public bool isMoving = false;
    private void Update()
    {
    if (isMoving)
    {
    Vector2 movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    if (movement.x != 0 || movement.y != 0)
    {
    rb.MovePosition(rb.position+movement);
    }
    }
    }
    private void OnMouseDown()
    {
    isMoving = true;
    }
    }

    any help or ideas?
     
  2. coidevoid

    coidevoid

    Joined:
    Oct 26, 2017
    Posts:
    55
    You will have to save the grid in an array, then check in target position in the array if the tile is actually blocked to prevent the move.
    Tell me if you need more help.
     
  3. Squitz

    Squitz

    Joined:
    Sep 29, 2019
    Posts:
    4
    Thanks for the tip.
    Just 1 slight issue. my objects consist of multible (should be blocked) tiles + they are also rotatable.
     
  4. coidevoid

    coidevoid

    Joined:
    Oct 26, 2017
    Posts:
    55
    Make smaller cells, and do a loop on all of them to check if there's a collider on them, then assign this grid as "blocked" if that's the case. Use OverlapCircle for that