【发布时间】:2020-06-08 11:41:47
【问题描述】:
我试图让玩家在我试图制作的 2D 自上而下的射击游戏中看着我的鼠标。我对四元数还没有任何经验,但我设法解决了对象旋转的常见问题。我还有其他问题,玩家根本没有指向鼠标,它只是指向某个随机方向。
Public Transform playerPos;
Private Vector3 mousePos;
// Define and look at mouse
void MouseL()
{
mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1);
Vector3 relativePos = mousePos - playerPos.position;
// rotate relativePos so the player will not rotate 90 deg in y axis
Vector3 rotatedRelativePos = Quaternion.Euler(0, 0, 90) * relativePos;
Quaternion rotation = Quaternion.LookRotation(Vector3.forward, rotatedRelativePos);
playerPos.rotation = rotation;
}
// Update is called once per frame
void Update()
{
MouseL();
}
即使 relativePos 确实发生了变化,但由于某种原因,玩家的旋转不会,无论我与玩家一起移动到哪里,似乎只有当 mousePos 确实发生变化时它才会旋转,但我将 relativePos 放入旋转中,所以我没有'不知道当 rotateRelativePos 发生变化时它是如何不旋转的。
编辑:如果 relativePos 发生变化,则旋转会发生变化,但非常轻微,例如整个屏幕上的 2 度。
编辑 2:设法用这段代码做到这一点:
Vector3 pz = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pz.z = 0;
var b = (pz.y - playerPos.position.y);
var a = (pz.x - playerPos.position.x);
var tang = a / b;
var radianRotation = Mathf.Atan(tang);
var degreeRotation = radianRotation * (180 / Mathf.PI);
if (pz.y < playerPos.position.y)
{
playerPos.rotation = Quaternion.Euler(0, 0, -degreeRotation + 180);
}
else { playerPos.rotation = Quaternion.Euler(0, 0, -degreeRotation); }
【问题讨论】:
-
为什么不直接使用反正切,因为它是二维的?然后你有一个旋转角度,就是这样
-
谢谢,我做到了,但我有同样的问题,
var a = Mathf.Abs(Input.mousePosition.y - playerPos.position.y); var b = Mathf.Abs(Input.mousePosition.x - playerPos.position.x); var tang = a / b; var radianRotation = Mathf.Atan(tang); var degreeRotation = radianRotation * (180 / Mathf.PI); playerPos.rotation = Quaternion.Euler(0, 0, degreeRotation);让我知道这是否有问题