Why my character stops when colliding?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Gonz4 L

I had make the character move like in pacman (constantly in one direction until hitting a wall) but how can I make the player to continue moving after hitting a wall?
This is my code:

extends KinematicBody2D

export (int) var speed = 1200
export (int) var jump_speed = -1800
export (int) var gravity = 4000

var velocity = Vector2.ZERO

func _physics_process(delta):
	if Input.is_action_just_pressed("ui_right") or Input.is_action_just_pressed("ui_left"):
		velocity.x = 0
		if Input.is_action_just_pressed("ui_right"):
			velocity.x += speed
		elif Input.is_action_just_pressed("ui_left"):
			velocity.x -= speed
	velocity.y += gravity * delta
	var snap = Vector2.DOWN * 16 if is_on_floor() else Vector2.ZERO
	velocity = move_and_slide_with_snap(velocity, snap, Vector2.UP)
	if Input.is_action_just_pressed("ui_up") and is_on_floor():
		velocity.y = jump_speed

Pd: I disabled snap when recording the gif.

:bust_in_silhouette: Reply From: Bean_of_all_Beans

So you are setting velocity to the returned value of move_and_slide_with_snap. This value, a Vector2, is the remainder of motion not travelled by move_and_slide_with_snap; basically when your character is moving through the air and collides with the side of the platform, move_and_slide_with_snap has moved as far left as it can go, but still has to go up, thus returning a value that might look like Vector2(0, 4). Since the Vector2.x is 0 but the Vector2.y is greater 0, you stop moving left or right, and will continue to move upwards a bit.

A simple fix is to just apply that lateral speed to velocity.x. Though, based on the GIF, if you are still holding LEFT, your character-box might not be clearing the CollisionShape2D of the platform, so it is simply going up, then dropping down.

I wasn’t holding left in the gif, just with pressing left or right once the character moves constantly in it’s respective direction and if I pressed left again after hitting the wall in the gif, the character would’ve been above of the platform like I want (if character’s height lets that happen of course) and not falling because of stopping right after colliding.
So I think the solution it’s just sum or substract depending on the direction speed to velocity again after hitting a wall.

Gonz4 L | 2020-12-26 14:17