简体   繁体   English

固定对角线运动

[英]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.我正在开发等距 3D 游戏。 I'm using Unity 2019.4我正在使用 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.您的问题的第一个主要线索应该是您计算了一个direction向量,但随后从未实际使用它。 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.这不会那么糟糕(浪费但不是世界末日),除了另一个主要问题是您以不同的方式计算rightMovementupMovement值。

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.如果某些事情不起作用,请查看已经存在的陈述并找出如何使它们变得更好(即使其发挥作用),而不是试图用更多的陈述来解决它们的任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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