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