Reputation: 12444
I just recently implemented gravity into my app however I just cannot get it to work properly. Whenever I execute my code, the character in my game drops instantly as if I am setting its position instead of applying gravity.
So I have the following code in my game loop (also dTime is delta time for my game loop):
float fVelocity = 0;
fVelocity -= GRAVITY * dTime;
velocity += fVelocity * dTime;
pos.y = clampf(velocity, -MAXSPEED, MAXSPEED);
Then gravity and MAXSPEED are defined like so:
#define GRAVITY 100
#define MAXSPEED 500
So is there anything here that looks wrong that could be causing this issue?
Thanks!
Upvotes: 1
Views: 147
Reputation: 8769
You are setting the position instead of the velocity. You don't show where you define your 'velocity' variable but I am assuming that it starts at zero. You need to initialise it with the actual position of your sprite if you are to do it the way you are doing it however you should probably try something where you define each variable differently making it easier to understand.
-- Inside you setup --
float acceleration = 0;
float velocity = 0
float positionY = 100;
-- Inside your update --
acceleration += -GRAVITY * dT;
velocity += acceleration * dT;
positionY += velocity * dT;
I didn't include the clamp but you can clamp to whatever you want.
As a side note some people do not like to multiply their variables with dT as if you have a frame rate drop the player will move a very large amount making it very hard to play games that require precise timing. If you don't multiply with dT the physics will lag with the game.
Upvotes: 2
Reputation: 929
A Max velocity of 500 pixels per frame is waaaay to high. Consider trying your algorithm with lower values for both gravity and maxspeed(id say around 10 gravity, 50 max speed), then tweak according to what you are seeing.
Upvotes: 0