1
\$\begingroup\$

First of all, I'm an absolute beginner in unity and coding so please excuse my lack of knowledge and my mistakes. I didn't achieve to fix my issue with others posts.

I'm trying to do a little top-down 2D RPG in which you move your character using the keyboard.


What I have for now:

  • The player can go in 8 directions,

Movements


  • The player rotation follows the directions smoothly using the rigidbody2D.rotation BUT although it works well for angle from 0° to 180° there is a problem with angle > 180° or < 0°. For example, the character is facing -135°, we want our character to go down which means 180°. Instead of going to -180 which is the same modulo 360° he turns the other way and do almost a full turn for just a 45° angle movement.

How the character move from -135° to 180°


I tried another solution by using transform.rotation and quaternions but I also have an issue with that method. While the movements work great, the velocity of the character seems affected by the Quaternion.Slerp because when the Slerp finishes, the character slow down.


The 2 rotation codes I tested (i do not use them simultaneously if you were wondering):

void GetRotation()
    {
        myRigidbody.rotation = Mathf.Lerp((myRigidbody.rotation), angle, angleRotation);
    }

void GetRotation()
    {
        Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, angleRotation);
    }

My movement code for one direction:

if (// Get Inputs)
    {
        angle = 0f;
        GetRotation();

        myRigidbody.velocity = Vector2.up * speed * Time.deltaTime;
    }

How would you fix that or what could I read to understand what goes wrong ?

Thank you in advance!

\$\endgroup\$
  • \$\begingroup\$ An Upvote for the quality of the question. \$\endgroup\$ – cmprogram Oct 26 '18 at 9:11
1
\$\begingroup\$

I finally found something that work for me :

void GetRotation()
    {
        if (myRigidbody.rotation <= -90 && angle >= 90)
        {
            myRigidbody.rotation += 360;
            myRigidbody.rotation = Mathf.Lerp(myRigidbody.rotation, angle, angleRotation);
        }

        if (myRigidbody.rotation >= 90 && angle <= -90)
        {
            myRigidbody.rotation -= 360;
            myRigidbody.rotation = Mathf.Lerp(myRigidbody.rotation, angle, angleRotation);
        }

        else
        {
            myRigidbody.rotation = Mathf.Lerp(myRigidbody.rotation, angle, angleRotation);
        }
    }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.