How would I make a CharacterBody2D bounce of another CharacterBody2D? Right now I have it bounce using position. Whenever a CharacterBody2D touches another CharacterBody2D its speed goes negative giving it a “bouncing” effect but it’s quite linear so it looks very robotic. How can I utilize physics to make them bounce off each other? (Code below)
Make sure to paste scripts instead of screen shots.
Character bodies should make use of their velocity
propertiy with either move_and_collide
or move_and_slide
. In your case I suppose move_and_collide
would be better.
First, do not edit position directly. calculate your movement vector then apply it.
func _physics_process(delta: float) -> void:
var move_vector: Vector2 = position.direction_to(player.position) * speed
var collision = move_and_collide(move_vector * delta)
if collision:
pass # do a bounce?!
Now using velocity
you can modify it over time to result in more fluid movement
extends CharacterBody2D
const ACCELERATION = 12 # speed * 4
@export var player: CharacterBody2D
func _physics_process(delta: float) -> void:
var move_vector: Vector2 = position.direction_to(player.position) * speed
velocity = velocity.move_toward(move_vector, ACCELERATION * delta)
var collision := move_and_collide(velocity * delta)
if collision:
velocity *= -1 # negative flip bounce
velocity = velocity.bounce(collision.get_normal()) # normal-based bounce
@export var player: CharacterBody2D
causes an error Invalid access to property or key 'position' on a base object of type 'Nil'.
When I replace it with get_parent().get_node("player")
no errors occur but there is no bounce on collision. The collision detection if statement does work though.
Did you copy and paste my sample or did you pick one of the two bounce lines? @export
variables need to be assigned; you already had player defined, but I would recommend making it a class variable instead of a local one, so Godot isn’t searching for the parent/player every frame.
I’ve assigned the export variable and I’ve tried both bounce methods and it still does not bounce
extends CharacterBody2D
var speed = 100
var ACCELERATION = 12
@export var player: CharacterBody2D
@onready var timer = $Timer
func _physics_process(delta: float) -> void:
var move_vector: Vector2 = position.direction_to(player.position) * speed
velocity = velocity.move_toward(move_vector, ACCELERATION * delta)
var collision := move_and_collide(move_vector * delta)
if collision:
velocity *= -1
Ah silly me, the sample was not using velocity
in move_and_collide
. you may need to increase the acceleration to 400, I like 4 times speed as a good base.
var collision := move_and_collide(velocity * delta)
thank you
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.