I’m using the code below for friction for my CharacterBody2D. The code works perfectly with keyboard controls or the DPAD on my PS4 controller. However, if I use the joystick on my PS4 controller I often get a constant small velocity that won’t reduce to zero. Does anyone know a resolution for this?
Here’s an example with the DPAD:
Here’s an example with the joystick:
This is the most relevant line of code:
velocity.x -= spd_inc * 0.5 * sign(velocity.x)
Here’s the relevant player movement code:
#control player
if Globals.is_alive0:
#horizonatal input
move_h = Input.get_axis('left0', 'right0')
#increase speed with time
if move_h:
velocity.x += spd_inc * move_h
if abs(velocity.x) > mv_spd:
velocity.x = mv_spd * move_h
#ground friction (slight player slide is intended)
if is_on_floor():
if abs(move_h):
animation.play('Walk2')
else:
if velocity.x != 0:
velocity.x -= spd_inc * 0.5 * sign(velocity.x)
animation.play('Slide2')
else:
animation.play('Idle2')
Okay, it only took a couple of minutes of playtesting to realize how dumb it would be to have a deadzone of 1 haha
Gertkeno sent me down the right path by bringing up deadzone, and it ultimately lead me to the resolution. The movement feels much better with a deadzone of .2 so I switched it to that from the default of .5.
I was able to resolve the friction issue with this code even while having a deadzone of .2:
move_h = Input.get_axis('left0', 'right0')
if move_h > 0:
move_h = 1
if move_h < 0:
move_h = -1
That way, if there is a move_h value less than abs(1), which was happening with the joystick, then move_h will be adjusted to -1 or 1
This in turn causes velocity.x to be an integer rather than a float. And therefore the friction will bring the player to a stop as intended with this line:
velocity.x -= spd_inc * 0.5 * sign(velocity.x)