move_and_collide

When using move_and_collide(), the function returns a KinematicCollision2D object upon collision. This object contains information about the collision and the colliding body. You can use this information to determine the response. Note that the function returns null when the movement was completed successfully with no collision.

For example, if you want the body to bounce off of the colliding object, you could use the following script:

extends KinematicBody2D

var velocity = Vector2(250, 250)

func _physics_process(delta):
    var collide = move_and_collide(velocity * delta)
    if collide:
        velocity = velocity.bounce(collide.normal)

Get Godot Engine Game Development Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.