I’m having a lot of difficulty trying to get horizontal movement working the way I want it to work. Here’s my code:
if self.velocity.x == math.abs(self.velocity.x) then
local speed1 = self.velocity.x + self.input.x * self.move_speed
local speed2 = self.input.x * self.max_speed
self.velocity.x = math.min(speed1, speed2)
else
local speed1 = self.velocity.x + self.input.x * self.move_speed
local speed2 = self.input.x * self.max_speed
self.velocity.x = math.max(speed1, speed2)
end
if self.input.x == 0 then
self.velocity.x = 0
end
Basically I want to be able to move left and right (controlled by the self.input vector) and then move up to max speed. Velocity should be set to 0 when both left and right keys are pressed, or when neither are pressed.
Right now the problem is that the velocity immediately rises to self.max_speed when moving left, but this code has gone through so many iterations over the past few days that I’m convinced there’s something fundamentally wrong with my approach.
Although it appears you are using whole integers when doing the calculations, I wonder if there might still be floating point issues.
In general, I’d advice against compares using “==”, since these are floating point numbers. Ofc, if it is guarantueed to be whole numbers, it should be ok.
You can read a bit more about floating point precision here.
If you are doing calculations in update() and don’t factor in delta time you will in a matter of frames (ie fractions of a second) end up at max speed.
I see that you’ve discarded the code from this post and I don’t really understand what you are doing with speed1 and speed2 in the snippet of code you shared. speed2 seems to be the be the horizontal max speed and speed1 is the current speed with movement factored in somehow.