Search code examples
c#unity-game-engine

I cant get the character to face the mouse position - Unity


I'm trying to make a simple top down shooter game for my first game in unity, I am by no means good at c#, I'm trying to get the player to face the direction of the mouse so that the player can aim at the enemies, however with my current code:

Vector3 input = Input.mousePosition;
     Vector3 mousePosition = Camera.main.ScreenToWorldPoint(new Vector3(input.x, input.y, Camera.main.transform.position.y));
     transform.LookAt(new Vector3(mousePosition.x, transform.position.y, mousePosition.z));

In the update method, but for some reason it faces the mouse in some positions, but doesn't in others. here is a video at what is happening https://youtu.be/--XU7_nRSOs` Thank you in advance. (this is my first time asking something on here)


Solution

  • As your camera is perspective and looking downward in an angle the

    Camera.main.transform.position.y
    

    as a distance parameter is most probably not resulting in the 3D position you are expecting.

    You should rather use e.g. a Raycast using ScreenPointToRay against a mathematical Plane that is parallel with your ground like e.g.

    // a ray shooting out of the camera into 3D space according to given screen point
    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    // an infinite mathematical plane parallel to the ground and at player height
    var plane = new Plane(Vector3.up, transform.position);
    // raycast against that plane - if hitting the plane the distance 
    // is the distance the ray traveled from its origin until hitting the plane  
    if(plane.Raycast(ray, out var distance))
    {
        // get the 3D intersection point of the ray with the plane
        var mousePosition = ray.GetPoint(distance);
        // look at this - it already is at the height of transform.position anyway
        transform.LookAt(mousePosition);
    }