F
Freddie The Potato
Guest
Heya!
I am struggling to find a solution to a problem that has plagued me for all eternity!
Imagine a 2D vector holding horizontal and vertical inputs:
Implementing player movement afterwards should be easy right?
Unfortunately we encounter a problem wherein if both xinput and yinput have non zero values, then the player's actual speed exceeds our desired top speed.
Fear not, for I have a solution! We can normalize the input vector to create a directional vector, then multiply its components by our speed value to get a velocity vector with a consistent length. What's more is that this solution also works with input methods that have more than 8 directions, such as gamepads.
But alas, we have another problem. I am unsure how to implement acceleration, friction and top speed into this approach. If the player is holding inputs, then they should accelerate towards the top speed in the specified direction, then decelerate to a stop when the player is not holding inputs.
xspd and yspd should not accelerate, decelerate or be clamped independently of each other, as this creates the janky and incorrect movement as seen in the first example above. I think speed and acceleration should be treated as 2D vectors.
Any help would be greatly appreciated. Thank you
I am struggling to find a solution to a problem that has plagued me for all eternity!
Imagine a 2D vector holding horizontal and vertical inputs:
Code:
xinput = keyboard_check(vk_right) - keyboard_check(vk_left);
yinput = keyboard_check(vk_down) - keyboard_check(vk_up);
Code:
spd = 4;
xspd = xinput * spd;
yspd = yinput * spd;
Fear not, for I have a solution! We can normalize the input vector to create a directional vector, then multiply its components by our speed value to get a velocity vector with a consistent length. What's more is that this solution also works with input methods that have more than 8 directions, such as gamepads.
Code:
//Normalize the input vector to create a directional vector
len = sqrt(sqr(xinput) + sqr(yinput));
xinput /= len;
yinput /= len;
//Multiply the directional components by speed to get true xspd and yspd
spd = 4;
xspd = spd * xinput;
yspd = spd * yinpit;
But alas, we have another problem. I am unsure how to implement acceleration, friction and top speed into this approach. If the player is holding inputs, then they should accelerate towards the top speed in the specified direction, then decelerate to a stop when the player is not holding inputs.
xspd and yspd should not accelerate, decelerate or be clamped independently of each other, as this creates the janky and incorrect movement as seen in the first example above. I think speed and acceleration should be treated as 2D vectors.
Any help would be greatly appreciated. Thank you