简体   繁体   中英

Fixing diagonal movement

I need help fixing my diagonal movement in unity. It goes faster diagonally than horizontally or vertically.

I'm working on an isometric 3D game. I'm using Unity 2019.4

Anyway here's my code:

if (canMove)
{
 Vector3 direction = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
 Vector3 rightMovement = right * moveSpeed * Time.deltaTime * Input.GetAxis("Horizontal");
 Vector3 upMovement = forward.normalized * moveSpeed * Time.deltaTime * Input.GetAxis("Vertical");

 Vector3 heading = Vector3.Normalize(rightMovement + upMovement);

 transform.forward = heading;
 transform.position += rightMovement;
 transform.position += upMovement;
}

The first major clue in your problem should be that you compute a direction vector but then never actually use it. That wouldn't be so bad (wasteful but not the end of the world), except that the other major problem is that you compute the rightMovement and upMovement values differently.

It seems to me that the code could be greatly simplified, having two benefits: making it more efficient, and making it easier to get right. Without a minimal, reproducible example it's impossible to say for sure what the right code is, but I would expect this to work in your case:

if (canMove)
{
    transform.forward = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
    transform.position += transform.forward * moveSpeed * Time.deltaTime;
}

Important tip: code doesn't always get better by adding more code to it. It's fine to add some statements experimentally during debugging to try things out, but it's generally a bad idea to just keep adding more and more statements. If something's not working, look at the statements that are already there and figure out how they can be made better (ie be made to work), rather than trying to fix whatever's wrong with them with even more statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM