Swami Gallardo
Swami Gallardo

Reputation: 37

Unity2D Character stutter with basic movement

I have the following character movement: If you press Space, character goes up. If you don't press Space, character goes down.

I'm trying to add some boundaries so the character can't go outside the zone. However i'm having some stuttering when the character reaches the top. What is the correct way to do this?

I've already tried adding the logic on FixedUpdate, doesn't fix it.

This is what's happening: GIF of my problem

This is the code:

private bool aboveSky = false;
private bool belowGround = false;

private float sky = -8f;
private float ground = -16.5f;

void Update () {
    float positionY = transform.position.y;
    aboveSky = positionY >= sky;
    belowGround = positionY <= ground;
    
    if (Input.GetKey(KeyCode.Space) && !aboveSky)
    {
        transform.Translate(-10f * Time.deltaTime, 0f, 0f);
    }
    else if (!belowGround)
    {
        transform.Translate(10f * Time.deltaTime, 0f, 0f);
    }
}

Upvotes: 0

Views: 168

Answers (1)

TEEBQNE
TEEBQNE

Reputation: 6266

It is jittering as you are approaching your threshold point, then continually exceeding it, then dropping and looping. Try to clamp the value after setting it. Clamping the value should smooth it out.

void Update()
{
    if(Input.GetKey(KeyCode.Space))
    {
        transform.Translate(0f, 10f * Time.deltaTime, 0f);
    }
    else
    {
        transform.Translate(0f, -10f * Time.deltaTime, 0f);
    }

    transform.position = new Vector3(transform.position.x, Mathf.Clamp(transform.position.y, ground, sky));
}

I am also not sure how you are moving in the y-axis when you are using the x component of the Translate method. Is your object rotate in an odd way? As I am not sure about the orientation of your object, you might need to tweak the above snippet to meet your needs.

Upvotes: 1

Related Questions