Unity 2D transfor.Translate motion is not smooth

I’ve no idea as to why is this happening…

Here’s my code :

#pragma strict

var speed = 3;
var uLimit = 25; var lLimit=10;


function Start () {
  
}

function Update () {
  
    if(this.transform.position.y > uLimit || this.transform.position.y <lLimit)
        speed *= -1;
  
    this.transform.Translate (0,Time.deltaTime * speed, 0);
  
  
}

The problem is the gameobject on which this code is applied to suffers from jitters sometimes.
Like out of 100 times, 90 times, the motion is smooth, but a few times, the gameobject freezes at its limits and starts to have jitters. For a couple of motion this persists after which the smooth motion is resumed. The gameobject has only a box collider attached to it. The gameobject is a dish-type sprite.
Any idea why? What could be a possible solution or fix?

I have a good guess as to why this is happening. Time.deltaTime changes every Update() cycle, so I’m guessing as you hit a boundary, you get a longish Time.deltaTime which pushes your object over the boundary kinda far-ish.

Now follow that up with a shorter frame. Yes, the object correctly changes direction, but since this new Time.deltaTime is too short, it doesn’t move back far enough to recross the boundary into the “safe” area.

Follow by another frame. Since the object is still past the boundary, the if statement is still true, and we change direction again thus pushing the object in the wrong direction for a frame.

A few frames of this direction changing and you should see jittering just beyond the boundary until another long Time.deltaTime comes along just as your object happens to be moving towards the center again pushing it back into “safe” territory.

// Only change speed if the speed is wrong!
if ((transform.position.y > uLimit && speed > 0) || (transform.position.y < lLimit && speed < 0))
2 Likes

Thanks a lot…
Appears to have solved the issue