uinty实现玩家跟随鼠标位置平滑旋转角度

 

 

 

首先我们要在场景中添加一个quad平面作为地板, 然后指定Layer为Floor,然后移除mesh renderer组件

然后添加脚本

脚本主要思想是从屏幕中心投出一条射线到地板, 然后获取对应坐标,然后转化成角度

最后然角色平滑转到该角度即可

 

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float turnSmoothing = 5f;
    public float rayLength = 100f;

    private int floorMask; 

    void Awake()
    {
        floorMask = LayerMask.GetMask("Floor");
    }

    void FixedUpdate()
    {
        TurningWithMouse();
    }

    void TurningWithMouse()
    {
        Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit floorHit;
        if (Physics.Raycast(camRay, out floorHit, rayLength, floorMask))
        {
            Vector3 playerToMouse = floorHit.point - transform.position;
            playerToMouse.y = 0f;
            Quaternion targetRotation = Quaternion.LookRotation(playerToMouse, Vector3.up);
            Quaternion newRotation = Quaternion.Lerp(rigidbody.rotation, targetRotation, turnSmoothing * Time.deltaTime);
            rigidbody.MoveRotation(newRotation);
            
        }
    }
}

 

 

欢迎公众号「后知后jue」,微信搜索关注回复「1024」,你懂的!

 

你可能感兴趣的:(Unity3D)