我想为unity(2D(制作一个简单的C#脚本。我想沿着我用鼠标点击的方向慢慢旋转一个对象(图像(。我一直在寻找它,只找到了如何在已知的方向上慢慢旋转,以及如何在我点击的地方旋转,但它并不慢。我试着把这两种机制结合起来,但都不起作用。这是我当前的一段代码:
Vector2 direction = new Vector2(0.0f, 0.0f);
void Update()
{
if (Input.GetMouseButtonDown(0))
{
destinationX = clicked('x');
destinationY = clicked('Y');
direction = new Vector2(clicked('x') - transform.position.x, clicked('y') - transform.position.y);
}
transform.Rotate(new Vector3() * Time.deltaTime * 10.2f, Space.World);
transform.position += transform.forward * Time.deltaTime * 0.2f;
}
float clicked(char axis)
{
if (axis == 'x')
{
return Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
}
else
{
return Camera.main.ScreenToWorldPoint(Input.mousePosition).y;
}
}
我知道它变得非常混乱,我不知道是否所有东西都被使用了,因为我失去了寻找答案的头脑(这就是我来这里的原因(。
请帮忙,谢谢
new Vector3()
作为参数传递给Rotate
。
这等于使用new Vector3(0,0,0)
,所以无论用什么乘以它,它都将保持0,0,0
=>您没有在任何轴上旋转对象。
您可能更想使用例如Mathf.Atan2
,它将为您提供Z旋转,以便查看相对于对象位置(==方向(的位置X、Y。
返回的值以弧度为单位,因此您还必须将其乘以Mathf.Rad2Deg
。现在知道了Z轴上所需的角度,就可以使用Quaternion.Euler
从该角度生成Quaternion
并将其存储(=targetRotation(。
最后,您可以使用Quaternion.RotateTowards
以线速度相对于目标旋转平稳旋转,而不会出现超调。
// Adjust these via the Inspector
// In angle per second
[SerializeField] private float rotationSpeed = 10.2f;
// In Units per second
[SerializeField] private float movementSpeed = 0.2f;
// If possible assign via the Inspector
[SerializeField] private Camera _camera;
private void Awake ()
{
// As fallback get ONCE
if(!_camera) _camera = Camera.main;
targetRotation = transform.rotation;
}
private Quaternion targetRotation;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
// Instead of 4 repeated calls store this ONCE
// directly use Vector2, you don't care about the Z axis
Vector2 destination = _camera.ScreenToWorldPoint(Input.mousePosition);
// directly use the Vector2 substraction for getting the direction vector without the Z axis
Vector2 direction = destination - (Vector2)transform.position;
// Use Atan2 to get the target angle in radians
// therefore multiply by Rad2Deg to get degrees
var zAngle = Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg;
// Store the target rotation
targetRotation = Quaternion.Euler(0,0, zAngle);
}
// Rotate smoothly with linear rotationSpeed against the targetRotation
// this prevents any overshooting
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
// In 2D you most probably do not want to move forward which is the Z axis but rather e.g. right on the X axis
transform.position += transform.right * Time.deltaTime * movementSpeed;
}
您可以使用四元数。勒普以平滑地旋转对象。
transform.rotation = Quaternion.Lerp(from.rotation, to.rotation, Time.time * speed);
您也可以使用Vector3.Lerp定位