Godot Version
v4.2.2.stable.official [15073afe3]
Question
In my game I have an object that the player can click on with the cursor and move around the screen and this object is a characterbody node. I want to make this characterbody be able to push away rigidbody nodes using impulses when the characterbody gets a collision with a rigidbody after move_and_slide and then applying an impulse to those bodies to push them away. The problem is that multiple impulses are getting called for a seemingly single collision. When I stepped through the code I realized the impulse wasn’t getting applied immediately and there were 2 calls to move_and_slide before any impulse is applied to the rigidbody so the characterbody collides twice with the rigidbody before it’s pushed away resulting in multiple impulses.
here is the concerning code inside the CharacterBody2D’s physics process function:
for i in get_slide_collision_count():
var c: KinematicCollision2D = get_slide_collision(i)
var rigid: RigidBody2D = c.get_collider() if c.get_collider() is RigidBody2D else null
if rigid:
var pushDir = -c.get_normal()
var diffVelInPushDir: float = max(0.0, velocity.dot(pushDir) - rigid.linear_velocity.dot(pushDir))
var massRatio: float = min(1.0, kgMass / rigid.mass)
var pushForce: float = massRatio * 5.0
# rigid.apply_impulse(pushDir * diffVelInPushDir * pushForce, c.get_position() - rigid.position)
var impulseAmt = pushDir * diffVelInPushDir * pushForce
rigid.apply_central_impulse(impulseAmt)
move_and_slide()
Would I need to setup a signal and trigger that after the impulse has been applied for the rigidbody before applying another impulse for that node or use await somehow to prevent this?