I'm generally new to this style of coding (mostly working in VBA before) and I could use some suggestions. I have my code typed out and it works exactly how I want it to as far as I can tell but it seems like it must be lengthier than it needs to be and I'm feeling somewhat insecure about the number of IF statements I have in this section of code. I would also appreciate it if you see a way to simplify the code, if you could explain how it works :)
I'm also confused why repeat statements work but using while statements don't.
This code is in Game Maker Studio 2 so it's generally similar to Java or C languages from what I've read online. This code is supposed to control the player's horizontal movement while also introducing some acceleration and friction.
Just for fun I also am including the original line of code that solved this problem before I started introducing these physics concepts (green means GO essentially).
The original code- The Original Code
hsp = 0; //horizontal speed
frctn = 0.8; //friction
acclrtn = 0.7; //acceleration
walksp = 6; //walk speed
dashsp = 12; //dash speed
var _keyLeft = keyboard_check(vk_left);
var _keyRight = keyboard_check(vk_right);
var _keyA = keyboard_check(ord("A"));
var _speed = walksp;
if(_keyLeft || _keyRight) //if left OR right are pressed
{
if (_keyLeft && _keyRight) //if left AND right are pressed
{
repeat(abs(hsp) > 1) //repeat the following while absolute value horizontal speed is greater than 1
{
hsp -= frctn * sign(hsp); //horizontal speed = horizontal speed - friction
}
if(abs(hsp) <= 1) hsp = 0; //if the horizontal speed is less than or equal to 1, then set to zero (to prevent negatives)
}
if (_keyA) _speed = dashsp; //if the A_Key is held, then set the _speed variable to the dash speed
repeat(abs(hsp) < _speed) //repeat if the absolute value of the horizontal speed is less than the _speed variable
{
hsp += (_keyRight - _keyLeft)*acclrtn; //Horizontal Speed = Horizontal Speed + (input of -1, 0, +1) * acceleration.
}
repeat(abs(hsp) > _speed) //repeat if the horizontal speed is greater than the _speed variable
{
hsp -= (_keyRight - _keyLeft)*frctn; //Horizontal Speed = Horizontal Speed + (input of -1, 0, +1) * friction.
}
}
else //if the left OR right key are NOT pressed
{
repeat(abs(hsp) > 0.5) //repeat if the absolute value of the Horizontal Speed variable is > 0.5
{
hsp -= frctn * sign(hsp); //horizontal speed = horizontal speed - friction
}
if(abs(hsp) <= 0.5) hsp = 0; //if the horizontal speed is less than or equal to 0.5, set to 0 (prevents negatives)
}