我正在尝试在Unity中制作一个简单的2D自上而下射击游戏。我有基本动作和鼠标跟随,但运动中存在问题。
每当你同时按下“向上”和“向右”时,它会按照您的预期对角移动,但是当你放开向上键时,它会沿对角线方向移动,我希望它向右移动。我处理运动的代码是:
private void Update ()
{
if (Input.GetKey(Up)) {
Debug.Log("UP");
Vector3 velUp = rigidbody2D.velocity;
velUp.y = walkSpeed;
rigidbody2D.velocity = velUp;
}
else if (Input.GetKey(Down)) {
Vector3 velDown = rigidbody2D.velocity;
velDown.y = walkSpeed*-1;
rigidbody2D.velocity = velDown;
}
else if (Input.GetKey(Left)) {
Vector3 velLeft = rigidbody2D.velocity;
velLeft.x = walkSpeed*-1;
rigidbody2D.velocity = velLeft;
}
else if (Input.GetKey(Right)) {
Vector3 velRight = rigidbody2D.velocity;
velRight.x = walkSpeed;
rigidbody2D.velocity = velRight;
}
else {
Vector3 velStop = rigidbody2D.velocity;
velStop.x = 0;
velStop.y = 0;
rigidbody2D.velocity = velStop;
}
//rotation
Vector3 mousePos = Input.mousePosition;
Vector3 objectPos = Camera.main.WorldToScreenPoint (transform.position);
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
}
我怎样才能让动作表现得像我提到的那样?它像对角线一样移动,使得运动看起来很偏离。
非常感谢任何帮助。感谢。
答案 0 :(得分:6)
以速度0开始,然后将所有移动方向相加。然后,您将矢量标准化并将其缩放到您的移动速度。否则,如果走对角线,玩家移动得更快。
我还没有检查过代码,但是这样的事情会发生:
void Update () {
Vector3 vel = new Vector3();
if(Input.GetKey(Up)){
Debug.Log("UP");
Vector3 velUp = new Vector3();
// just use 1 to set the direction.
velUp.y = 1;
vel += velUp;
}
else if(Input.GetKey(Down)){
Vector3 velDown = new Vector3();
velDown.y = -1;
vel += velDown;
}
// no else here. Combinations of up/down and left/right are fine.
if(Input.GetKey(Left)){
Vector3 velLeft = new Vector3();
velLeft.x = -1;
vel += velLeft;
}
else if(Input.GetKey(Right)){
Vector3 velRight = new Vector3();
velRight.x = 1;
vel += velRight;
}
// check if player wants to move at all. Don't check exactly for 0 to avoid rounding errors
// (magnitude will be 0, 1 or sqrt(2) here)
if (vel.magnitude > 0.001) {
Vector3.Normalize(vel);
vel *= walkSpeed;
rigidbody2D.velocity = vel;
}
//rotation
Vector3 mousePos = Input.mousePosition;
Vector3 objectPos = Camera.main.WorldToScreenPoint (transform.position);
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
}
关于Normalize
,请查看此图片。
如果你只向上或向右走,你会以速度1移动(我们后来乘以你想要的速度)。但如果你走对角线,你走的速度大约是所需速度的1.4倍(绿色矢量)。 Normalize
保持向量的方向完整,但是给出一个长度(也称为#34;幅度")为1(红色向量)。
在老年射击游戏中你可能会发现一个名为"bunny hopping"的错误。我不确定这是否是问题的根源,但我猜它是。
关于vel.magnitude > 0.001
:
我们实际上想知道是否vel.magnitude > 0
。但vel.magnitude
是计算的结果,因此可能包含舍入误差。如果您使用浮点值,请始终牢记这一点。检查本身已完成,因为Normalize
方法需要除以幅度,除以零是邪恶的。不确定Normalize
是否会自行检查。
答案 1 :(得分:0)
在没有任何按键被按下的情况下,似乎唯一一次强制你的速度为空。
我可能会建议添加一些检查以查看Input.GetKeyUp
何时true
,并将rigidbody2D.velocity
的{{1}}或x
值设置为y
,也许是这样的:
0