我想旋转我的NavigationMeshAgent参照鼠标的位置。下面是我这样做的代码。
public class Navcontroller : MonoBehaviour
{
// Start is called before the first frame update
private NavMeshAgent _agent;
void Start()
{
_agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
float horInput = Input.GetAxis("Horizontal");
float verInput = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horInput, 0f, verInput);
Vector3 moveDestination = transform.position + movement;
_agent.destination = moveDestination;
}
}不巧的是,旋转是奇怪的,当我移动鼠标的时候,它可以看遍整个地方。我遗漏了什么?
更新:
我已经用鼠标的位置更新了我的代码如下,
public class Navcontroller : MonoBehaviour
{
// Start is called before the first frame update
private NavMeshAgent _agent;
float mouseX, mouseY;
float rotationSpeed = 1;
void Start()
{
_agent = GetComponent<NavMeshAgent>();
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float horInput = Input.GetAxis("Horizontal");
float verInput = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horInput, 0f, verInput);
Vector3 moveDestination = transform.position + movement ;
mouseX += Input.GetAxis("Mouse X") * rotationSpeed;
mouseY -= Input.GetAxis("Mouse Y") * rotationSpeed;
_agent.destination = moveDestination;
_agent.transform.rotation = Quaternion.Euler(mouseY, mouseX, 0);
}}
现在代理和相机一起旋转。但这名特工并没有朝他所看到的方向移动。
发布于 2020-09-30 19:54:42
基于评论
Vector3 mousePosition = Input.mousePosition; // Get mouse position
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition); //Transfom it to game space - form screen space
Vector2 direction = new Vector2(
mousePosition.x - transform.position.x,
mousePosition.y - transform.position.y
); // create new direction
transform.up = direction; // Rotate Z axis因为基于评论,这与NavigationMeshAgent或AI无关。那么,要向前迈进,你要做的
if(Input.GetKey(Key.W)){
transform.forward += Speed * Time.deltaTime;
}编辑
您的_agent.destination = moveDestination;需要匹配您的旋转,所以您需要乘以它的旋转。_agent.destination = Quaternion.Euler(mouseY, mouseX, 0) * moveDestination,moveDestination应该相对于它的旋转(不是像现在这样绝对的),所以最好使用_agent.destination = Quaternion.Euler(mouseY, mouseX, 0) * Vector3.forward
https://stackoverflow.com/questions/64144375
复制相似问题