The way the program works is as follows:
The jump method starts by updating the objects y velocity and location without respect for collisions.
vely+=grav;
if(jumpok==true && dbSpaceKey()){
vely=-dbSqrt(-2.*grav*(height));
}
y+=vely;
Then the program does a simple check to see if the object has gone below ground level and if it should be restored to ground.
if(y>=ground){
vely=0;
jumpok=true;
y=ground;
}else{
jumpok=false;
}
Then the position is updated but I don't believe you actually need this line.
Then, the code checks to see if a collision has occurred. If one has, the program will know to only alter the y coordinates due to the collision. This, of course, only works if the sprites are not rotated.
if(dbSpriteCollision(1001,1003)){
if(vely>0){
y=dbSpriteY(1003)-dbSpriteHeight(1001)-1;
jumpok=true;
}else{
y=dbSpriteY(1003)+dbSpriteHeight(1003)+1;
}
vely=0;
}
The above code could be looped using several objects allowing the creation of large worlds.
In more detail:
If vely>0 then the object is moving down. Therefore, the object must be on top of the object with which it collided.
The object is moved to just above the top of the static object.
y=dbSpriteY(1003)-dbSpriteHeight(1001)-1;
This way there is no longer a collision. However there will be a visible gap unless the visible sprite is not the same as the collision sprite.
Since we went down, we are standing on something that is facing up. Therefore, we can jump.
"jumpok=true;"
The opposite happens when you are going up and of course in either case your new velocity is 0.
Then the position is updated again.
In leftright:
The object is moved according to the left and right keys.
if(dbLeftKey()){
x-=move;
dbSprite(1001,x,y,1);
}
if(dbRightKey()){
x+=move;
dbSprite(1001,x,y,1);
}
Once again, the only movement is in the x so we know how to reposition the object when there is a collision.
Here instead of using the velocity to determine which side the object should be on I used the position just because it is easier.
However, the velocity method is more reliable when the velocity is extremely high, but you should never have your objects moving that fast because you risk passing the object without touching it.
if(dbSpriteCollision(1001,1003)){
if(x>dbSpriteX(1003)){
x=dbSpriteX(1003)+dbSpriteWidth(1003)+1;
}else{
x=dbSpriteX(1003)-dbSpriteWidth(1001)-1;
}
}
We update the position.
I hope this answers your question!