Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Stop Unity from moving diagonally using transform translate

I have a game in which the character can only move horizontally and vertically, not diagonally.

I have tried to implement this with this code, which should check if the player is pressing down/up or left/right:

if (Input.GetKey("down"))
{
    moveHor = false;
    moveVer = true;
    if(moveVer == true)
    {
        transform.Translate(Vector3.down * Time.deltaTime * speed);
    }
}
if (Input.GetKey("up"))
{
    moveHor = false;
    moveVer = true;
    if (moveVer == true)
    {
        transform.Translate(Vector3.up * Time.deltaTime * speed);
    }
}
if (Input.GetKey("right"))
{
    moveVer = false;
    moveHor = true;
    if(moveHor == true)
    {
        transform.Translate(Vector3.right * Time.deltaTime * speed);
    }
}
if (Input.GetKey("left"))
{
    moveVer = false;
    moveHor = true;
    if (moveHor == true)
    {
        transform.Translate(Vector3.left * Time.deltaTime * speed);
    }
}

This code is ran in the Update() method.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The thing is, it’s not working and I can’t figure out why.

I hope someone knows what to do.

>Solution :

Try to use else-if to translate only in one direction per update cycle.
I’ve also removed nested if statements from your code, which were redundant and unneeded.

if (Input.GetKey("down"))
{
    moveHor = false;
    moveVer = true;

    transform.Translate(Vector3.down * Time.deltaTime * speed);
}
else if (Input.GetKey("up"))
{
    moveHor = false;
    moveVer = true;

    transform.Translate(Vector3.up * Time.deltaTime * speed);
}
else if (Input.GetKey("right"))
{
    moveVer = false;
    moveHor = true;

    transform.Translate(Vector3.right * Time.deltaTime * speed);
}
else if (Input.GetKey("left"))
{
    moveVer = false;
    moveHor = true;

    transform.Translate(Vector3.left * Time.deltaTime * speed);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading