C# 如果玩家从目标向相反方向移动,当玩家注视目标时,如何旋转身体?
脚本将附加到装备中的角色颈部。因此,当运行游戏时,如果我移动目标(注视),玩家站着不动,玩家头部将注视目标 问题是当目标静止时,我移动玩家,因此如果我将玩家移动到远离目标的另一个方向,玩家的颈部(头部)仍在旋转,看着目标,但身体朝向移动的方向,因此头部看着目标,身体朝向移动的方向 我认为逻辑应该是,如果我将玩家移动到某个方向,头部应该朝着移动方向向前看,并且只有当玩家移动到观察目标区域方向时,才能再次观察目标C# 如果玩家从目标向相反方向移动,当玩家注视目标时,如何旋转身体?,c#,unity3d,C#,Unity3d,脚本将附加到装备中的角色颈部。因此,当运行游戏时,如果我移动目标(注视),玩家站着不动,玩家头部将注视目标 问题是当目标静止时,我移动玩家,因此如果我将玩家移动到远离目标的另一个方向,玩家的颈部(头部)仍在旋转,看着目标,但身体朝向移动的方向,因此头部看着目标,身体朝向移动的方向 我认为逻辑应该是,如果我将玩家移动到某个方向,头部应该朝着移动方向向前看,并且只有当玩家移动到观察目标区域方向时,才能再次观察目标 但我不知道怎么做。如何使颈部朝向其移动的方向,并且仅当移动到目标区域时,才查看目标。您
但我不知道怎么做。如何使颈部朝向其移动的方向,并且仅当移动到目标区域时,才查看目标。您应该添加一个布尔函数,该函数仅在玩家能够看到敌人时才返回true。您可以这样做:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LookAtTarget : MonoBehaviour
{
public Transform lookAt;
public Vector3 defaultFacing;
public float angleLimit = 60f;
public float rotationDamping = 3f;
// Start is called before the first frame update
void Start()
{
}
// Using late update so animations don't overwrite my transform manipulations...
void LateUpdate()
{
// For this example i'll be using the root objects forward vector as what i want to be my reference constraint vector.
// You might want to use something else though.
defaultFacing = transform.root.forward;
// The direction from this transform, pointing at the look at target.
Vector3 directionToLookAtTarget = lookAt.position - transform.position;
float angle = Vector3.Angle(directionToLookAtTarget, defaultFacing);
// Since i'm just using the root objects forward vector as a constraint, i can just use its rotation as my default rotation instead of calculation a Quaternion.LookAt.
Quaternion defaultRotation = transform.root.rotation;
// The look at rotation to the target if it were completely unrestrained.
Quaternion lookAtCompleteRotation = Quaternion.LookRotation(directionToLookAtTarget);
Quaternion finalRotation = Quaternion.identity;
// If the angle is greater than our limit, return a rotation that is in the direction of the lookAtCompleteRotation but is limited to the angle we chose as a limit.
// Otherwise, if its within our limit, we just return the rotation as is.
if (angle > angleLimit)
finalRotation = Quaternion.Euler(transform.forward);
//finalRotation = Quaternion.Slerp(defaultRotation, lookAtCompleteRotation, angleLimit / angle);
else
finalRotation = lookAtCompleteRotation;
transform.rotation = Quaternion.Slerp(transform.rotation, finalRotation, Time.deltaTime * rotationDamping);
}
}