Search code examples
c#unity-game-enginenavigationagent

Navmesh Agent rotate with mouse


I would like to rotate my NavigationMeshAgent with reference to the mouse position. Following is my code to do so.

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;

    }
}

Unforutnately , the rotation is weird and it can look all over the place as I move the mouse. what am I missing?

UPDATE:

I have updated my code with the mouse position as follows,

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);

}

}

Now that the agent rotates with the camera. But the agent is not moving in the same direction where he is looking at.


Solution

  • Based on the comment

    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
    

    Because based on the comment this has nothing to do with NavigationMeshAgent or AI. Then to move forward you do

    if(Input.GetKey(Key.W)){
        transform.forward += Speed * Time.deltaTime;
    }
    

    EDIT

    Your _agent.destination = moveDestination; needs to match your rotation so you need to multiply it by the rotation. _agent.destination = Quaternion.Euler(mouseY, mouseX, 0) * moveDestination where moveDestination should be relative to its rotation (not absolute as you probably have now) so better use _agent.destination = Quaternion.Euler(mouseY, mouseX, 0) * Vector3.forward