[英]Disabling diagonal movement in Unity 5 2D? (using C#)
或更确切地说,我应该说“有效地禁用对角线运动”。
在线上有很多Q / A,但是我一直遇到相同的问题:水平移动(例如,向左)时,我可以覆盖当前方向并开始垂直移动(通过向上推),这是我想要的。 但这反过来是行不通的! 垂直运动不能替代水平运动。
void Update () {
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
ManageMovement(h, v);
}
void ManageMovement(float horizontal,float vertical) {
if (vertical != 0f) {
horizontal = 0f;
Vector3 movement = new Vector3 (horizontal, vertical, 0);
GetComponent<Rigidbody2D> ().velocity = movement * speed;
return;
}
if (horizontal != 0f) {
vertical = 0f;
Vector3 movement = new Vector3 (horizontal, vertical, 0);
GetComponent<Rigidbody2D> ().velocity = movement * speed;
return;
} else {
Vector3 noMovement = new Vector3 (0, 0, 0);
GetComponent<Rigidbody2D> ().velocity = noMovement;
}
}
如果我颠倒了这些if()语句的顺序,那么就可以解决问题。 所以,这是一个线索。 但是我不是一个伟大的侦探。 我希望有帮助!
使用输入。 GetAxisRaw而不是GetAxis。
GetAxis以-1到1的比例返回浮点数。返回到0的速度取决于轴设置。 如果将重力设置为非常高的数字,它将更快地返回到0。 如果将灵敏度设置为很高的数值,它将更快地变为-1或1。
因此,根据这些设置,您的函数ManageMovement将被调用多次,并逐渐改变水平和垂直值。
随着时间的推移,输入内容可能如下所示:
Update #1: ManageMovement(0.2, 1.0)
Update #2: ManageMovement(0.3, 0.9)
...
Update #N: ManageMovement(1.0, 0.0)
因此,当您检查vertical!= 0时,它将保持非零,直到它实际达到0,然后再将所有这些更新设置为horizontal为0。
GetAxisRaw不会以这种方式进行平滑。
尝试将else语句添加到ManageMovement方法:
void ManageMovement(float horizontal,float vertical) {
if (vertical != 0f) {
horizontal = 0f;
Vector3 movement = new Vector3 (horizontal, vertical, 0);
GetComponent<Rigidbody2D> ().velocity = movement * speed;
return;
}
else if (horizontal != 0f) {
vertical = 0f;
Vector3 movement = new Vector3 (horizontal, vertical, 0);
GetComponent<Rigidbody2D> ().velocity = movement * speed;
return;
} else {
Vector3 noMovement = new Vector3 (0, 0, 0);
GetComponent<Rigidbody2D> ().velocity = noMovement;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.