Unity:使用Lerp / Slerp围绕Z轴旋转对象

时间:2014-06-17 23:20:35

标签: rotation unity3d

我试图将我的播放器旋转到我上次点击的位置。我实际上已经做了这个,但是现在我想看到玩家以设定的速度旋转而不是精灵只是瞬间改变旋转。 我尝试了几种我在网上找到的方法,但它们都不适合我。这就是我所拥有的

void Update()
{
   if (Input.GetMouseButtonDown (0)) 
   {

            Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
            diff.Normalize();
            float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
            transform.rotation= Quaternion.Euler(0f, 0f, rot_z - 90);


            Instantiate(ProjectilePrefab, transform.position, transform.rotation);
        }
}

上面的代码工作正常,但它没有显示任何移动。我试图这样做,但位置错误,轮换也是即时的:

Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
var newRotation = Quaternion.LookRotation(diff);
newRotation.y = 0.0f;
newRotation.x = 0.0f;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 30);

任何想法?

2 个答案:

答案 0 :(得分:2)

这里有两个问题。首先,Slerp函数仅在用户按下鼠标按钮后调用一次。你必须将它移到if部分之外或使用协程。其次,Slerp要求从01的浮动表示进度,而不是timedeltaTime。覆盖lerp函数的官方示例很糟糕,因为使用time值只能在游戏运行的第一秒内起作用。

你需要这样的东西

if (Input.GetMouseButtonDown (0)) {
    // your other stuff here
    float starTime = Time.time;
}
float t = Time.time - startTime;
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, t);

旋转将在一秒钟后完成。如果您想要更快或更慢,只需将t与因子相乘。

答案 1 :(得分:0)

我找到了答案。这就是我的工作方式

 if (Input.GetMouseButtonDown (0)) {
                    target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
                    rotateToTarget = true;
                    print ("NEW TARGET: " + target);
            }

            if (rotateToTarget == true && target != null) {                             
                    print ("Rotating towards target");


                    targetRotation = Quaternion.LookRotation (transform.position - target.normalized, Vector3.forward);
                    targetRotation.x = 0.0f;//Set to zero because we only care about z axis
                    targetRotation.y = 0.0f;

                    player.transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);  



                    if (Mathf.Abs (player.transform.rotation.eulerAngles.z - targetRotation.eulerAngles.z) < 1) {

                            rotateToTarget = false;
                            travelToTarget = true;
                            player.transform.rotation = targetRotation;
                            print ("ROTATION IS DONE!");
                    }
            }