Having problems trying to make player face mouse

The code i made is the following:

using UnityEngine;

public class Player : MonoBehaviour
{
    public GameObject projectilePrefab;
    public Transform wandTip;

    Vector3 movementInput;
    public Rigidbody playerRB;
    public Transform playerGO;
    public float playerSpeed;

    Vector2 mousePos;
    Vector2 mousePosInWorld;
    Vector3 pointToLookAt;
    public Camera mainCam;
    void Start()
    {

    }
    void Update()
    {
        movementInput = new Vector3 (Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
        mousePos = Input.mousePosition;
        mousePosInWorld = mainCam.ScreenToWorldPoint(mousePos);
        print(mousePosInWorld);
        //pointToLookAt = new Vector3(mousePosInWorld.x, playerGO.transform.position.y, mousePosInWorld.y);
        //print(pointToLookAt) ;
    }
    void FixedUpdate()
    {
        playerRB.MovePosition(playerRB.position + movementInput * playerSpeed * Time.fixedDeltaTime);
        //playerGO.LookAt(pointToLookAt);
    }
}

Instead of telling me where the mouse position as a world point is, it tells me the camera x and y coordinates…
Im a noob dont flame me please and thank you :slight_smile:

Camera.ScreenToWorldPoint() wants a Vector3 where the z value defines the distance from the camera. Input.mousePosition returns a Vector3 where the z value is zero. Therefore you get the actual camera position.

just add this line after retrieving Input.mousePosition and before executing Camera.ScreenToWorldPoint():

mousePos.z = 1; // you can use any value which makes sense as a distance for you instead
1 Like

Thank you