How can I do the smoothed rotation on Unity?

Asked

Viewed 37 times

-3

Hello! I’m testing a 2D, platform-style drive. Basically, I want when the player presses "A," it rotates to the right. I managed to do it, but I want him to turn around, not just out of nowhere he already turns right....

    [Header("Main")]
    public int Speed;

    [Header("Inputs")]
    float HorizontalInput;

    [Header("Others")]
    Rigidbody2D Rig;

    // Start is called before the first frame update
    void Start()
    {
        Rig = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        Move();

        Rotate();
    }

    void Move()
    {
        HorizontalInput = Input.GetAxis("Horizontal");
        Rig.velocity = new Vector2(HorizontalInput * Speed, Rig.velocity.y);
    }

    void Rotate()
    {
        if(HorizontalInput > 0)
        {
            transform.rotation = Quaternion.Euler(0, HorizontalInput * 0, 0);
        }

        if(HorizontalInput < 0)
        {
            transform.rotation = Quaternion.Euler(0, HorizontalInput * (180 * -1), 0);
        }
    }

I tried this Script, it is turning to the left normally, but when I turn to the right, it already goes straight... (Try to put this code in Unity to understand better, I tried to put a video but it seems that it is not possible in Stackoverflow.

1 answer

1

Computers have processors that do billions of operations per second, following this logic when you run a code that is in an infinite cycle (Update) it will do that MANY times per second, so fast it seems that it teleports...

To fix this in any drive situation to be more realistic you need to multiply by Time.deltaTime is a very low number that will depend on the speed of your machine, causing it to stay at "smoother values".

I’ll just give you an example of how you could do.

Rig.velocity = new Vector2(HorizontalInput * Speed * Time.deltaTime, Rig.velocity.y);

And another thing because it’s taking Horizontal Input and multiplying by 0? That will always result in 0, so it doesn’t rotate on the other side...

Last important point is the function

transform.rotation = Quaternion.Euler(0, HorizontalInput * (180 * -1), 0);

will assign the rotation in Eulers directly to Transform, you are not taking the current rotation and adding values. To rotate relative to the current position you could use the function Rotate.

If you really only want a single drive with interpolation you can use directly set the Eulerangles using Lerp.

I recommend that first of all do tutorials for beginners, have a very good on youtube and also whenever you have in doubt look at the documentation of Unity that is very well made and complete.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.