0 votes


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.

Godot version 3.2.3
in Engine by (122 points)

1 Answer

0 votes
Best answer

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.

by (339 points)
selected by

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.