• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

GameMaker Hspeed Movement Problems (SOLVED)

hans

Member
I'm making a game where the player's movements have inertia to them. I'm having a problem in my code where the hsp variable is building up and creating jerky movements. Is there any way I can have the hsp be limited so the sudden jerk doesn't happen? Here is the step event for obj_player

Code:
var w = keyboard_check_pressed(ord("W"));
var d = keyboard_check(ord("D"));
var s = keyboard_check(ord("S"));
var a = keyboard_check(ord("A"));
var falling = !collision_point(x,y + 32,obj_parent_block,0,0);
var sped = 2;
var tsped = 20; //Terminal Velocity


/////////////Movement


if d
{
    hsp += sped;
    hspeed = min(hsp, tsped);
}
else
if hspeed > 0
{
    hspeed = max(hspeed - sped, 0);
}


if a
{
    hsp -=sped;
    hspeed = max(hsp,tsped * -1);
}
else
if hspeed < 0
{
    hspeed = min(hspeed + sped, 0);
}
 

YoSniper

Member
Are you using the built-in attribute hspeed or are you using the user-defined attribute hsp?

I highly recommend either one or the other. Once we've established that, we can fix the code further.
 

hans

Member
I'm using Hspeed to manipulate the speed and hsp as a buffer to have an acceleration and not an instant 1 - 11 surge of speed.
 

YoSniper

Member
Okay, so if hsp is your acceleration, then I recommend renaming it to reflect that.

Here's an example code for your problem. A or D will accelerate the object one way or the other, and both keys (or neither key) pressed will cause the object to decelerate.

Code:
var w = keyboard_check_pressed(ord("W"));
var d = keyboard_check(ord("D"));
var s = keyboard_check(ord("S"));
var a = keyboard_check(ord("A"));
var falling = !collision_point(x,y + 32,obj_parent_block,0,0);
var accel = 2;
var terminal_speed = 20; //Terminal Velocity


/////////////Movement

if d - a == 0 { //Both keys pressed or neither pressed. Decelerate to zero.
    if abs(hspeed) <= accel {
        hspeed = 0;
    } else {
        hspeed -= sign(hspeed) * accel;
    }
} else { //One of the two keys pressed
    hspeed += (d - a) * accel;
    if abs(hspeed) > terminal_speed {
        hspeed = sign(hspeed) * terminal_speed;
    }
}
 

hans

Member
Thank you for the solution and looking at your code I learned what abs and sign does. This works Perfectly. Thanks for the help. :)
 
Top