如何控制旋转刚体的速度?

时间:2017-11-03 03:17:56

标签: c# unity3d

我有一个旋转的物体始终面向鼠标,但旋转是即时的。我想减慢旋转速度,以便用户慢慢转向面向鼠标指针。

我正在使用此处的代码: https://unity3d.com/learn/tutorials/projects/survival-shooter

以下是我遇到问题的代码片段:

        // Create a ray from the mouse cursor on screen in the direction of the camera.
        Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);

        // Create a RaycastHit variable to store information about what was hit by the ray.
        RaycastHit floorHit;

        // Perform the raycast and if it hits something on the floor layer...
        if(Physics.Raycast (camRay, out floorHit, camRayLength, floorMask))
        {
            // Create a vector from the player to the point on the floor the raycast from the mouse hit.
            Vector3 playerToMouse = floorHit.point - transform.position;

            // Ensure the vector is entirely along the floor plane.
            playerToMouse.y = 0f;

            // Create a quaternion (rotation) based on looking down the vector from the player to the mouse.
            Quaternion newRotation = Quaternion.LookRotation (playerToMouse);

            // Set the player's rotation to this new rotation.
            playerRigidbody.MoveRotation (newRotation);
        }

1 个答案:

答案 0 :(得分:0)

此链接的解决方案应该有效,因为它逐渐向所寻求的轮换方向发展。

https://answers.unity.com/questions/1093355/rotate-object-smoothly-over-time-when-key-pressed.html

 public float smooth = 1f;
  private Quaternion targetRotation;
  void Start(){
           targetRotation = transform.rotation;
  }

  void Update () {
      if (Input.GetKeyDown (KeyCode.Space)) { 
          targetRotation *=  Quaternion.AngleAxis(60, Vector3.up);
      }
      transform.rotation= Quaternion.Lerp (transform.rotation, targetRotation , 10 * smooth * Time.deltaTime); 
  }