Navmesh Agent 用鼠标旋转

Navmesh Agent rotate with mouse

我想参考鼠标位置旋转我的 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);

}

}

现在代理随相机旋转。但是代理人并没有朝着他正在看的同一个方向移动。

根据评论

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