Unity之用物理的方法跟随鼠标转向并移动

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControl : MonoBehaviour
{

public float speed = 5;
private Rigidbody playerRigidbody;
// Use this for initialization
void Start()
{
    playerRigidbody = transform.GetComponent();
}
void Update()
{

    PlayerMove();
    Turning();

}

void Turning()
{
    // 创建一个物理射线,获取鼠标的坐标
    Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);

    // 我这里判断的是射线打击到地面
    RaycastHit floorHit;

    // 表示只检测第8层
    LayerMask floorMask = 1 << 8;

    // 如果射线打击到物体,并且物体属于floorMask层
    if (Physics.Raycast(camRay, out floorHit, 1000, floorMask))
    {
        // 获取鼠标点到地面上的点和人物当前坐标之间的向量差
        Vector3 playerToMouse = floorHit.point - transform.position;

        // 设置差值的y轴的角度为0
        playerToMouse.y = 0f;

        // 计算角度
        Quaternion newRotation = Quaternion.LookRotation(playerToMouse);

        // 赋值给人物
        playerRigidbody.MoveRotation(newRotation);


        ///另一种转向角度的获取方式,通过两向量夹角获取,不过不能搭配Rigidbody.MovePosition方法使用会有冲突而产生卡顿
        // float roation = Vector3.Angle(Vector3.forward, playerToMouse);
        // roation = playerToMouse.x > 0 ? roation : -roation;
        // Debug.Log("roation=" + roation + "floorhit=" + floorHit.point);
        // transform.eulerAngles=new Vector3(0,roation,0);
    }
}

private void PlayerMove()
{
    //使用系统预设的w,a,s,d 控制Cube移动
    float h = Input.GetAxis("Horizontal");
    float v = Input.GetAxis("Vertical");
    Vector3 dir = new Vector3(h, 0, v);
    //刚体移动的特点:物体的位置+方向,太快就方向*一个小数,使之慢一点
    playerRigidbody.MovePosition(playerRigidbody.position + dir * Time.deltaTime * speed);
}

}

你可能感兴趣的:(Unity之用物理的方法跟随鼠标转向并移动)