Create rotation towards mouse position

I tried quaternion, transform.lookat, angleAxis etc… but can’t figure out why my character start moving different direction instead of rotating around the Y as towards the mouse.

I have debugged the camera.inworld position

public class CharacterController : MonoBehaviour
{
 
    public float movSpeed = 15;

    private Rigidbody body;

    // Start is called before the first frame update
    void Start()
    {
        body = gameObject.GetComponent<Rigidbody>();
    }
 
    void FixedUpdate()
    {
        PlayerMove();
        PlayerRotate();
        Debug.Log(Camera.main.ScreenToWorldPoint(Input.mousePosition));
    }

    public void PlayerMove()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");

        var time = Time.fixedDeltaTime;

        body.transform.Translate(h * movSpeed * time, 0, v * movSpeed * time);
    }

    public void PlayerRotate()
    {
        // Get mouse position
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        Vector3 lookDir = mousePos - body.position;
        Quaternion rotation = Quaternion.LookRotation(lookDir, Vector3.up);
        transform.rotation = rotation;

    }  

}


ScreenToWorldPoint takes a Vector3, and Input.mousePosition is a Vector2. A Vector2 can convert into a Vector3, so there’s no problem, right? Except, when it does, it puts a 0 into the Z position. ScreenToWorldPoint uses the Z position as the distance from the camera. So if you put in a Vector3 with the Z being 0, it’s always going to just give you the position of the camera, because it’s 0 units away!
You need to either
A) create a Vector3, with mousePosition’s X and Y but a Z value that you choose, that is, the distance from your camera to the plane
B) Use Physics.Raycast to cast from the camera to your plane, and use the resulting hit.point as your look target.

1 Like

@CodeWurm

Well @StarManta answered while I was typing… but here is my answer anyway.

This won’t ever work with 3D camera:

Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

You’ll simply get some point somewhere in front of camera, it most likely won’t be on where you expect it to be (= on grass surface / ground plane).

You’ll have to use Raycasting to get point on collider surface and use that for your look direction instead.

With orthographic camera ScreenToWorldPoint can be used as is, as there is no need for distance parameter IIRC.

I think it actually gives you a point on the near clipping plane of the camera but the rest of this is accurate.

1 Like

I studied this code it makes sense

public void PlayerRotate()
    {
        RaycastHit hit;

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if(Physics.Raycast(ray, out hit))
        {
            transform.LookAt(new Vector3(hit.point.x, transform.position.y, hit.point.z));
        }
    }

This might be another question, but maybe you guys know.
I cant make this navmesh working, anybody can help? I’m getting this errors.

This is my zombie:

public NavMeshAgent agent;

    private GameObject player;

    void Start()
    {
        NavMeshAgent agent = GetComponent<NavMeshAgent>();
        player = GameObject.FindGameObjectWithTag("Player");
    }

    // Update is called once per frame
    void Update()
    {
        Die();
        FollowPlayer();
    }

    void Die()
    {
        if (health <= 0)
        {
            Destroy(this.gameObject);
        }
    }

    void FollowPlayer()
    {
        agent.SetDestination(player.transform.position);
    }

Errors:

"SetDestination" can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.AI.NavMeshAgent:SetDestination(Vector3)
Zombie:FollowPlayer() (at Assets/Scripts/Zombie.cs:38)
Zombie:Update() (at Assets/Scripts/Zombie.cs:25)

My zombies in scene:

Failed to create agent because it is not close enough to the NavMesh

Did you try navmesh methods for moving agent instead of using transform? Like NavMeshAgent.Warp?

To find point in navmesh for agent, you can use NavMesh.SamplePosition.

Doesn’t matter what i try it keeps complaing the same error.

“Doesn’t matter what i try it keeps complaing the same error.”

Can’t see your code, pretty hard to say anything.

I tried warp instead of spawning at the objects spawns, they start spawn in the middle and start rotating, whatee??

  void FollowPlayer()
    {
        if (zombie)
        {
            zombie.destination = player.transform.position;
            // zombie.Warp(player.transform.position);
        } else {
            Debug.Log("No agent!");
            }
    }

I really dont know what is wrong everything stand on the ground, followed multiply tutorials inclusive the official one from unity, this is really frustrating, killedthe motivation for the project.

… how could anyone help unless you share your code.

It could be something obvious or maybe not.

Now everyone else will simply be guessing what you are doing.

This is with zombie.destination
6409146--715680--nav1.PNG
this one is with zombie.warp

Ah I fxed my problem but why all the objects go to the center instead of the player