A* Pathfinding Project

Rotation in 2D game (Top-Down)


#1

Hello! Do you have a lesson about writing a script about the rotation of the character during his walk? If not, you can write an example of such a script (how to calculate it and use it in the movement script), because I did not find it on the Internet.

  • (Yes, I read the documentation. I used and studied the AIPath script, but I did not come to a conclusion)
    ** (Oh, if you notice errors in the text, English is not my native language)

#2

Hi,

Below is some code to find the current direction, and rotate towards that direction. This code was based on the example for custom movement here: https://arongranberg.com/astar/docs/old/custom_movement_script.php

            Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;

// The step size is equal to speed times frame time.
        float step = rotationSpeed * Time.deltaTime;

        Vector3 newDir = Vector3.RotateTowards(transform.forward, dir, step, 0.0f);

        // Move our rotation a step closer to the target.
        transform.rotation = Quaternion.LookRotation(newDir);

My apologies for the formatting, I’m on mobile.
There are numerous ways of handling the rotation, also do note this isn’t 2d specific. There might be some small changes to be made.

The key component is the Quaternion.LookRotation, Quaternion.LookAt is also a great function to make use of.

Wolf


#3

How can I optimize this for 2D


#4

Thank!
But how to make it rotate only along the Z axis?


#5

The AIPath script has a toggle for ‘Orientation’ you can use that to set an orientation appropriate for most 2D games. If you set it to YAxisForwards then it will only rotate around the Z axis.


#6

I did it, but it did not help. Perhaps it needs to be "include " into transform.rotation ?

Code and Unity screens click


#7

Hi

That PlayerMover script is something you have written which does not seem to use the orientation mode at all (just adding it as a field to your script doesn’t do anything). The AIPath script has an orientation mode that it uses. If you write your own script you will need to write your own rotation code that can do the same thing.


#8

Ohhh … Ok. I have 2 ways:

  1. I need to write a script like this.
  2. use AIPath
    Using my script is useless, since it is not possible to use a turn. I understand correctly?

#9

Yes, you have those two options essentially.