Handling Player Jump:
In many kind of games, we will have to implement 'jump' feature for our player / hero. It's really simple to achieve it. First of all as you probably will conclude, you will need physics.
- Create new physics world - check this article for more info.
- I assume you already have your hero sprite with its body - if not, check previous articles.
- Lets create method responsible for jumping.
- To do it, you may for example setLinearVelocity to your body.
public void jump() { //play jump sound playerBody.setLinearVelocity(new Vector2(playerBody.getLinearVelocity().x, -13.5f)); }
As you can see, its really simple, all you have to do, is to adjust last parameter (Y value) which is responsible for jump. That's all, now your hero might finally jump.
Be aware, that here I described only really simple way how to handle it, with this way, player may jump infinitely many times, there is no restriction. Do change it, below I will describe easy way how to prevent doing so:
- create new int field, responsible for 'foot contacts'.
- Using Contact Listener on begin contact, increase this value++
- on end contact, decrease this value--
- In jump method, add special check:
if (footContacts < 1)
return;
With this simple way, you will disable possibility to jump without any restriction (in this case, without touching ground first)
HTML Comment Box is loading comments...