How do I make it so that it bounces the other direction

Godot Version

godot 4

Question

right know the var direct is hard coded to go right and it looks like it’s bounce off the right white plane, but how do I get it so that it goes in the other direction?


do I need to add collider or change the var type?

1 Like

Try declaring the direction outside / before the function, then change it’s value within the function when you collide.

e.g. along the lines of:

extends CharacterBody2D

var speed = 450
var direction = Vector2.RIGHT

func _physics_process(delta):
    var collision = move_and_collide(direction * speed * delta)
    if collision:
        direction = collision.get_normal()

Alternatively I think you can just use the velocity,
e.g. along the lines of:

extends CharacterBody2D

var speed = 450

func _ready():
    velocity = Vector2.RIGHT * speed

func _physics_process(delta):
    if get_slide_collision_count() > 0:
        velocity = get_slide_collision(0).get_normal() * speed
    move_and_slide()

Apologies if the above code doesn’t work as naughtily I haven’t tried it.

Edit:
I’ve now tested both of the above and they work for a simple left / right scenario.
However I didn’t add the bounce direction which changes the direction of the bounce based on the current direction, so here is a correction for the first one:

extends CharacterBody2D

var speed = 450
var direction = Vector2.RIGHT

func _physics_process(delta):
    var collision = move_and_collide(direction * speed * delta)
    if collision:
        direction = direction.bounce(collision.get_normal())

This is what I came up with for bouncing off “multiple objects” - I expect there are a number of better ways of doing it. Note that in my testing I found the velocity once a bounce had occurred wasn’t what I expected, hence the use of old_direction variable, and it reports multiple collisions in circumstances where there aren’t multiple objects (I’m not sure why).

extends CharacterBody2D

var speed = 450
var old_direction

func _ready():
	velocity = Vector2.RIGHT * speed
	old_direction = velocity.normalized()

func _physics_process(_delta):
	var surfaces = get_slide_collision_count()
	if surfaces > 0:
		var surface_normal = Vector2.ZERO
		for surface in get_slide_collision_count():
			surface_normal += get_slide_collision(surface).get_normal()
		old_direction = old_direction.bounce(surface_normal.normalized())
		velocity = old_direction * speed
	move_and_slide()

PS I’m presuming your scene has colliders to bounce off of.