Skip to content

Instantly share code, notes, and snippets.

@Shilo
Last active March 23, 2024 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shilo/ae51a977ad6b1c3cc4775f1d3053118f to your computer and use it in GitHub Desktop.
Save Shilo/ae51a977ad6b1c3cc4775f1d3053118f to your computer and use it in GitHub Desktop.
Godot 2d character ability to push rigid bodies.
class_name CharacterPush2D extends Node
@export var character: CharacterBody2D
@export var push_strength: float = 1000
@export var pushable_body_group: String = "pushable_body"
@export var lock_x: bool = false
@export var lock_y: bool = false
@export var no_physics: bool = false
@export var disabled: bool = false
func _ready():
var parent = get_parent()
character = parent if parent is CharacterBody2D else character
func _physics_process(delta: float):
_physics_process_push(delta)
func _physics_process_push(delta: float):
if disabled || !character:
return
for i in character.get_slide_collision_count():
var collision := character.get_slide_collision(i)
var collider := collision.get_collider()
if collider is RigidBody2D && collider.is_in_group(pushable_body_group):
var push_direction := -collision.get_normal()
if lock_x:
push_direction.x = 0
if lock_y:
push_direction.y = 0
var push_collider := _push_collider if no_physics else _push_collider_physics
push_collider.call(collider, push_direction, delta)
func _push_collider_physics(collider: RigidBody2D, direction: Vector2, delta: float):
collider.apply_central_impulse(direction * push_strength * delta)
func _push_collider(collider: RigidBody2D, direction: Vector2, delta: float):
collider.move_and_collide(direction * push_strength * delta / 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment