How to make a player move one unit in a grid?

Updated on April 10, 2018 in General
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
2 on April 9, 2018

Hello everyone,

I’m trying to make a grid-based movement for my player. I succeeded in moving the player over a fixed distance in every direction, but I don’t know how to implement so my player can’t move more than one unit in this grid at a time. Practically I mean by this that once the player moved one unit of the fixed distance, he /she needs to press the arrow key again to move another unit. I don’t want the player to be able to keep moving by keep pressing down an arrow key.

This is my code now:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {
public float speed = 2.0f; // Speed of movement
public float distance = 0.5f; // Distance between grid positions
public float xBoundary = 3f; // Limit player’s movement on the x axis
public float yBoundary = 4.5f; // Limit player’s movement on the y axis
Vector3 pos; // For movement

void Start()
{
pos = transform.position; // Take the initial position
}

void FixedUpdate()
{
if (Input.GetKey(KeyCode.LeftArrow) && transform.position == pos && pos.x > -xBoundary)
{ // Left
Vector3 left = new Vector3 (- distance, 0, 0);
pos += left;
}
if (Input.GetKey(KeyCode.RightArrow) && transform.position == pos && pos.x < xBoundary)
{ // Right
Vector3 right = new Vector3 (distance, 0, 0);
pos += right;
}
if (Input.GetKey(KeyCode.UpArrow) && transform.position == pos && pos.y < yBoundary)
{ // Up
Vector3 up = new Vector3 (0, distance, 0);
pos += up;
}
if (Input.GetKey(KeyCode.DownArrow) && transform.position == pos && pos.y > -yBoundary)
{ // Down
Vector3 down = new Vector3 (0,- distance, 0);
pos += down;
}
transform.position = Vector3.MoveTowards(transform.position, pos, Time.fixedDeltaTime * speed); // Move there
}
}

Thank you in advance!

Ruben

  • Liked by
Reply
0 on April 10, 2018

The way I would do it would be to instantiate a Vector3[ x , y ] (a bidirectional array of size x * y of your choice), and the I would fill the grid with a double for loop like:

for(int x = 0; x<grid.Length; x++){
    for(int y = 0; y < grid[x].Length; y++){
        grid[x,y] = new Vector3(x, y, 0); //or Vector3(x, 0, y) depending on the axis you with to make the player move on
    }
}

 

This way you could regulate the movement of the player with the grid cells, and you could take the destination of every movement from the grid itself

  • Liked by
Reply
Cancel
0 on April 10, 2018

Thank you, that idea worked!

  • Liked by
Reply
Cancel