How can I calculate rotations with Character Controller

Hello.
I’m working on Enemy Pathfinding for my game, but I am running into issues when trying to rotate the enemies in the direction they are moving. Whenever I try to use something like

Quaternion rotation = Quaternion.LookRotation(player.position - transform.position);
transform.rotation = rotation;

The enemy starts moving in an arc around where I want it to go.

Here is my movement code:

        if(Vector3.Distance(transform.position, player.position) <= 50 && Vector3.Distance(transform.position, player.position) >= 1)
        {
            Vector3 movePosition = transform.TransformDirection(player.position - transform.position);
            Vector3 move = transform.forward * movePosition.z + transform.right * movePosition.x;
           
            characterController.Move(move * speed * Time.deltaTime);


        }

I know I need to do something with the Move(), but I don’t know what.

This code is wrong:

Vector3 movePosition = transform.TransformDirection(player.position - transform.position);

TransformDirection accepts a LOCAL SPACE vector and converts it into WORLD SPACE. You have input a world space vector, so the output is going to be nonsense.

It’s also unclear to me what this line should be doing:

Vector3 move = transform.forward * movePosition.z + transform.right * movePosition.x;
1 Like

Move towards the player:

        float distance=Vector3.Distance(transform.position, player.position);
        if (distance > 1 && distance < 50)
        {
            Vector3 moveDirection = (player.position - transform.position).normalized;
            characterController.Move(moveDirection * speed * Time.deltaTime);
        }

Or move in the direction the enemy is looking.

       float distance=Vector3.Distance(transform.position, player.position);
        if (distance > 1 && distance < 50)
        {
            characterController.Move(transform.forward * speed * Time.deltaTime);
        }
2 Likes

what does normalized do?

You can just consult the docs: https://docs.unity3d.com/ScriptReference/Vector3-normalized.html

1 Like