1
我有一个游戏物体在我的场景,我想这游戏物体转动,使得它面临着我的鼠标,当我点击它。旋转后,它应该朝着它现在面临的方向移动。但它几乎可行。
例
例如可以说斜边是:4.592912和相邻的是:3.042814,然后我需要MathF.Cos(相邻/斜边)= 0.6625021,现在我采取MathF.Acos(0.6625021) * MathF.Rad2Deg =从现场37.95857
GIF:
代码
float mouseX, mouseY;
float playerX, playerY;
float squaredDeltaX, squaredDeltaY;
float hypotenuse;
int dirX, dirY;
float rotation;
bool mouseClicked = false;
void Update() {
UpdateInputs();
if (mouseClicked)
{
CalcDistance(playerX,playerY,mouseX,mouseY);
SetRotation(squaredDeltaX, squaredDeltaY, hypotenuse);
}
}
void UpdateInputs()
{
Vector3 pos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
mouseX = pos.x;
mouseY = pos.y;
playerX = transform.position.x;
playerY = transform.position.y;
mouseClicked = Input.GetMouseButtonDown(0);
}
void CalcDistance(float x, float y, float x1, float y1)
{
dirX = (x - x1) >= 0 ? 1 : -1;
dirY = (y - y1) >= 0 ? 1 : -1;
squaredDeltaX = (x - x1) * (x - x1);
squaredDeltaY = (y - y1) * (y - y1);
hypotenuse = Mathf.Sqrt(squaredDeltaX + squaredDeltaY);
print("squaredDelta: " + squaredDeltaX + ", " + squaredDeltaY);
print("Hypotenuse: " + hypotenuse);
print("delta: " + Mathf.Sqrt(squaredDeltaX)*dirX + ", " + Mathf.Sqrt(squaredDeltaY)*dirY);
}
void SetRotation(float opposite, float adjacent, float hypotenuse)
{
float tempOpposite = Mathf.Sqrt(opposite);
float tempAdjacent = Mathf.Sqrt(adjacent);
rotation = Mathf.Acos(Mathf.Cos(tempOpposite/hypotenuse));
print("MathF.Cos: " + rotation);
rotation *= Mathf.Rad2Deg * dirX;
print("MathF.Acos: " + rotation);
rotation = dirY != -1 ? rotation + 180 : rotation;
print("angle: " + rotation + "*");
transform.eulerAngles = new Vector3(1,1,rotation);
}
非常感谢,我会试试! :) –
欢迎您:-)顺便说一下,使用https://gamedev.stackexchange.com/来提出与游戏相关的问题,对于这些问题,这是一个比这更好的地方! – Aybe