//获取目标方向
Quaternion rotation=Quaternion.LookRotation(player.position-transform.position);
//插值趋近
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * speed);
player指的是玩家 speed可以认为是旋转速度吧。
这一就解决了缓慢旋转的功能。
接下来,我们只需要把玩家的高度与NPC的高度保持一致,那就实现了我们需要的效果了.
下面是代码:
Update(){
//玩家的x,z与NPC的y作为一个新的vector3
Vector3 v = new Vector3(player.position.x,transform.position.y,player.position.z);
Quaternion rotation=Quaternion.LookRotation(v-transform.position); //获取目标方向
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * speed); // 差值 趋向目标
}
完整代码如下:(新建FacePlayer脚本,并将此脚本挂在NPC身上)
//Create by RedDefine 2017/03/07
using UnityEngine;
public class FacePlayer : MonoBehaviour
{
private Transform player;
public float speed = 1f;
void Start()
{
player = GameObject.FindWithTag("Player").transform;
}
void Update()
{
Vector3 v = new Vector3(player.position.x, transform.position.y, player.position.z);
Quaternion rotation = Quaternion.LookRotation(v - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * speed);
}
}