We are trying to make a mario game.However the character used is going up and up if we are holding the up key.Unlike the mario game in which it comes back after a certain height.We have just started learning Gml. Please help us with this thing.We have uploaded the script which we have made for the jumping and moving. hsp and vsp variables are for horizontal and vertical speed respectively.grav is for setting the gravity.
{
var hsp;
var vsp;
var grav;
var grounded;
hsp = 0;
vsp = 0;
grav = 5;
grounded = 0;
key_right = keyboard_check_direct(vk_right);
key_left = keyboard_check_direct(vk_left);
key_up = keyboard_check_direct(vk_up);
if(key_right)
{
if(hsp < 3)
{
hsp += 5;
}
}
if(key_left)
{
if(hsp > -3)
{
hsp -= 5;
}
}
if(key_up)
{
vsp = -20;
}
vsp += grav;
if(place_meeting(x + hsp, y, obj_wall))
{
while(!place_meeting(x + sign(hsp), y, obj_wall))
{
x += sign(hsp);
}
hsp = 0;
}
x += hsp;
if(place_meeting(x, y + vsp, obj_wall))
{
while(!place_meeting(x, y + sign(vsp), obj_wall))
{
y += sign(vsp);
}
if(sign(vsp) == 1)
{
grounded = 1;
}
vsp = 0;
}
else
grounded = 0;
y += vsp;
}
Your problem is with the code:
if(key_up)
{
vsp = -20;
}
vsp += grav
What's happening is that every step, if the up key is pressed, the object executing the script will be moved 20px up. It will then move the character down by grav
px. Since grav
is always 5, this will result in a net displacement of (-20 + 5) = -15
as long as the up key is pressed. It's like you are constantly (as long as up is pressed) jumping every step, instead of just one jump and then letting gravity do its job.
I think what you want is to only jump if you have something underneath you (to jump off of). To do this, simply add another condition (checking if you are on top of something) to the if
statement, like this...
if ( key_up and place_meeting(x, y+1, obj_wall) )
{
vsp = -20;
}
vsp += grav
Now, you will only be able to jump if you are standing on something, and gravity will pull you down if you are in midair.