- Home /
Grid-based movement with auto-move
Hi, I`m working on grid-based movement, that will continously move a game object at a constant speed in one of 4 directions. For example, if I press A it keeps moving left until I press D, so that it starts moving right, but in a grid-based way, so that I cannot turn other direction before it reaches another grid (center, I guess?). The problem is that I have a script that allows to walk in a grid-based way, but I`m having a hard time implementing auto-moving.
Here`s the script
Vector3 pos;
float speed = 2f;
// Use this for initialization
void Start () {
pos = transform.position;
}
// Update is called once per frame
void FixedUpdate () {
if (Input.GetKey (KeyCode.A) && transform.position == pos) {
pos += Vector3.left;
}
if (Input.GetKey (KeyCode.D) && transform.position == pos) {
pos += Vector3.right;
}
if (Input.GetKey (KeyCode.W) && transform.position == pos) {
pos += Vector3.up;
}
if (Input.GetKey (KeyCode.S) && transform.position == pos) {
pos += Vector3.down;
}
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
}
Answer by SneakyLeprechaun · Aug 24, 2017 at 02:04 PM
I would suggest using a variable like Vector3 dir
that stores the direction you want your object to go in. To change value, simply put the following, changing as needed:
if(Input.GetKeyDown(KeyCode.A){ dir = Vector3.left; } else if(Input.GetKeyDown(KeyCode.D){ dir = Vector3.right; }
and so on and so forth. Then, just put
transform.position += dir;
at the end.
Also, you may have a reason for this, but I would suggest using the Input.GetButtonDown()
function instead of the Input.GetKeyDown()
function since it makes your code a little more flexible.