I have some problem with “Jump” I don’t have the result I would like. Actually, wth the Jump part of the code, my player go a little into the platform and I don’t know why. More over, If I continue to press space button my player become crazy by shaking very fast and I don’t want that. I would like that the player has to release the space button before do another jump.
There it is the code to make my “player” jump :
public void playerUpdate(GameTime gameTime)
KeyboardState kState = Keyboard.GetState();
float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
hitBoxPlayer = new Vector2(position.X + 45, position.Y + 35);
// Fall because of gravity part code
Vector2 tempPos = position;
tempPos.Y += speed * increment * dt;
tempPos.X += speed * increment * dt;
if (Platform.DidCollideVertical(tempPos) && Platform.DidCollideHorizontal(position))
jumping = false;
position.Y += speed * increment * dt;
if (increment < 10)
increment += 0.1f;
jumping = true;
Your code is a little mess (no offense :)) so I’ll try to give a general guidelines to simple platform jumping and falling.
What you want to do is to maintain a velocity Y for the player, which is the speed he moves on y axis every frame. Positive is falling down, negative jumping up, or the other way around its your choice.
So every frame you’ll have something like:
position.y += velocity.y * elapsedTime
Now assuming positive is down, every frame the player feet don’t touch the ground, the y velocity should increase by your gravity factor (up to a certain max so he won’t fall too fast). When hitting ground, it should zero velocity y. Something like:
Ye this a working approach. Any suggestion on how achieve the same mechanic without having to release the jumpbutton to actually jump? I’d like the same behavior but at the same time always initiate the jump at button pressed.
I guess we could cancel any remaining minus value on the velocity y when and if the button i released.
EDIT: Got it working. What i did was to increase the gravity if the jumpbutton is released before the jump reach its returnpoint (velocity.y = 0):
this of cource requires that you keep track of whether the jumpbutton is still pressed or not. You could go 1 step further and actually increase the gravity based on how quick the button was released.Your default velocity.Y will be ticking down towards 0 and the gravity could be adjusted depending on how close you are (lesser if closer).