# Trying to make sprite float up and down [closed]

Using LibGDX + Box2D and my understanding of the answer posted from this question: Here

I apply the following impulse:

// modify sprite's Box2d Body object
int a = 8; // amplitude
int f = 1; // frequency
int p = 1; // phase
float value = (float) ( a * Math.sin( 2 * Math.PI *f * TimeUtils.millis() + p ) );
body.applyLinearImpulse( 0, value, body.getPosition().x, body.getPosition().y, false );

// render it
sprite.setPosition( body.getPosition().x, body.getPosition().y );
sprite.draw( spriteBatch );


But this just causes my sprite to go straight up and offscreen rather than doing a wave. What part of the algorithm am I doing wrong?

• I suspect you need to use smaller values for amplitude and frequency. Anyway you are using to calculate linear impulse. The function actually calculates the Y position of the object. you are using that Y value to apply an impulse, which will cause multiple impulses to cause the object to fly away. Then when Y is negated it will have the opposite force direction. Feb 12, 2014 at 10:55
• Thanks concept3d, your explanation was helpful. So if currently I'm calculating the Y position instead of the necessary impulse, how can I modify the formula so that it calculates the impulse instead? Feb 12, 2014 at 11:44
• it depends on what are you trying to achieve? You don't necessarily need this formula. Feb 12, 2014 at 11:55
• This question appears to be off-topic because it is about debugging your code for you.
– Anko
Feb 12, 2014 at 12:34

TimeUtils.millis()


Maybe you mean to do:

final long floatyPeriod = 3000; //3 secs
long now   = TimeUtils.millis();
long delta = lastTime - now;
lastTime = now;
object.floatyTime += delta;
if (object.floatyTime > floatyPeriod )
object.floatyTime -= floatyPeriod;

...

float value = (float) ( amplitude * Math.sin( 2 * Math.PI * frequency * object.floatyTime/1000 + phase ) );


I don't understand how your code would make it go straight up though, I think it should wobble up and down like crazy with yours.

• To be honest, I'm not sure. I got the idea of using the now time from here, specifically line 367 of main. Originally I was just modifying the body's Y coordinate like they did, but I changed to applying impulse instead because body.setTransform() doesn't render as smoothly. Feb 12, 2014 at 11:48