Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Best way to simply move on a grid layout?

Discussion in '2D' started by n-carlson1, Apr 15, 2016.

  1. n-carlson1

    n-carlson1

    Joined:
    Jul 11, 2015
    Posts:
    5
    Similar to the 2DRoguelike tutorial, I want my character to move on a grid-like pattern, where he moves a specific amount each way every time. My problem is, after watching the roguelike tutorial i realized that is WAY more complicated than what I'm looking for. Is there a foolproof/glitch proof way to simply implement that movement?

    All I'm basically looking for is the character to move left/right/up/down let's say 30 pixels each time. I know I can use if get key down, transform.position.x +=30; or something to that tune but that seems to get a little weird at times and I don't know if that's the most foolproof way to do it. I was planning on adding in a lerp or something so it's smooth, but I don't think that's the main concern. The main concern is getting the movement down though.
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    Wherever you move your character, make sure you round his position to the nearest Tile Size (30 in your scenario) once the movement is done. You're probably dealing with floating point errors by adding and subtracting to position.
     
  3. JymWythawhy

    JymWythawhy

    Joined:
    Jan 18, 2015
    Posts:
    25
    I use grid based movement in my game, and I have a "MoveTo" function that takes an X and a Y coordinate (I made an int based Vector2 class that I pass in, but you could just send it the coordinates as ints). My tiles are each one Unity unit in dimension, so the coordinates fit the unity coordinate system. The function sets the position of my sprite to the coordinate passed and handles lerping the sprite to that location.

    In practice, to move 1 tile up I say something like "MoveTo(position.x, position.y +1);".

    I hope that helps.
     
  4. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    Additionally if your tiles are all 30x30, make sure all your sprites are using a Pixels Per Unit of 30, so that 1 unity unit = 30 pixels.