Hi all
If the character is in the air, it can be jumping or falling.
It is needed to have something like the code below, where difs is a vector that contains the values that should be subtracted to the Y coordinate from 0 up to 29 (jumping up) indices and then added from 30 up to 59 (jumping down); if the character lands on the floor before reaching the index 59, then it is not in the air any more and the jump (let's say JumpAndFall) process ends; if the character reachs the index 59 and there's no floor under its feet, then it will continue falling (adding a constant to the Y coordinate) up to it finds the floor, or, in the worst case, it falls to the void and loses a life.
When you press the jump key, AND if you are on the ground, then you need to set index = 1 and position = Positions.Jumping; if you walk and you are not steping on the floor any more, then you just need to set position = Positions.JumpAndFall (index is 0 and then you just fall).
I took this from my Mario game and adapted to be generic.
// this loads into the difs vector the values referred above - they could be stored and loaded from a file if preferred
for (a = 1; a < 31; a++)
difs[a - 1] = (int)(Math.Round(Math.Sin(a * 3 * Math.PI / 180.0) * jumpMaxHeight - Math.Sin((a - 1) * 3 * Math.PI / 180.0) * jumpMaxHeight));
for (a = 31; a < 61; a++)
difs[a - 1] = difs[60 - a];
// (suppose that jump starts with index = 1 and set position to Positions.JumpAndFall, which makes the below method to execute)
private void JumpAndFall()
{
if (index > 0 && index < 31)
{
if (!Ceiling())
Y -= difs[index - 1];
else
index = 60 - index;
}
else if (index > 30)
Y += difs[index - 1];
else if (index == 0)
Y += 8;
if (Floor() && (index > 30 || index == 0))
{
index = 0; position = Positions.Stand; // the hero landed
}
if (index > 0 && index < 60)
index++;
else
index = 0;
}
Hope this helps