first of, this bug doesn’t become apparent until later in the course, when walls are added. But it does relate to the Player movement code, so I thought I’d post it here.
Basically, the code adds to the movement vector, no matter whether the character is actually moving. So by letting the character walk into a wall, you can build up the movement to max speed and then inch around the corner and get a “running start”. I made a little clip to illustrate:
It’s not too tragic or could even be considered a feature (“sprinting around a corner”)
Nevertheless, I thought I’d take a shot at fixing it and I’m looking for some feedback on the code. I added these functions that use the collision information of the last
move_and_slide call and some vector operations to figure out whether the character is pressing against a wall in one of the four directions:
func get_last_collision(): if get_slide_count() > 0: return get_slide_collision(get_slide_count() - 1) return null func is_colliding_in_direction(direction): var collision = get_last_collision() if collision: var angle = collision.normal.angle_to(direction) return abs(angle) < deg2rad(45) return false func is_on_left_wall(): return is_colliding_in_direction(Vector2.RIGHT) func is_on_right_wall(): return is_colliding_in_direction(Vector2.LEFT) func is_on_top_wall(): return is_colliding_in_direction(Vector2.DOWN) func is_on_bottom_wall(): return is_colliding_in_direction(Vector2.UP)
And then I use these in the movement code conditions, e.g.:
if Input.is_action_pressed('ui_left') and not Input.is_action_pressed('ui_right') and not is_on_left_wall(): motion.x = clamp(motion.x - SPEED * delta, -MAX_SPEED, 0)
This way, the character only builds speed to the left, if it is not running into a wall to its left.
This works for me and fixes the behaviour, but I’m wondering whether there’s a better way to do it? Is using the collision normal the way to go to fix stuff like this?