unity3d vector3.forward中游戏对象旋转时如何旋转到特定点

af7jpaap  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(127)

My player is the cube and the target is sphere

`void Update()

{

    Vector3 direction = target.position - player.transform.position;
    Quaternion rotation = Quaternion.LookRotation(direction);

    if (Input.GetMouseButton(0))

    {

        player.transform.rotation = Quaternion.RotateTowards(player.transform.rotation, Quaternion.Euler(player.transform.rotation.x, player.transform.rotation.y, rotation.z), rotationSpeed * Time.deltaTime);

    }

    else

    {

        player.transform.Rotate(-Vector3.forward * 1f);
    }

}
`

播放器无限旋转,就像一个球形移动与变换旋转。当我点击我想旋转我的播放器到目标位置。我试图与旋转朝向,但它旋转到0。我该如何解决这个问题,或者我应该做其他事情。

zd287kbt

zd287kbt1#

所以首先Quaternion的x,y,z并不是你所期望的那样!它们与欧拉角无关,并且在-11之间的归一化范围内移动。
然后假设你只在Z轴上旋转player**,那么你可以简单地使用,例如

void Update()
{
    // use Vector2 to eliminate any delta on the Z axis
    // -> vector is only in XY space
    Vector2 direction = target.position - player.transform.position;
    // -> rotation is only on Z axis
    Quaternion rotation = Quaternion.LookRotation(direction);

    if (Input.GetMouseButton(0))
    {
        player.transform.rotation = Quaternion.RotateTowards(player.transform.rotation, rotation), rotationSpeed * Time.deltaTime);
    }
    else
    {
        player.transform.Rotate(-Vector3.forward * Time.deltaTime);
    }
}

相关问题