How to make a bullet push an enemy?

Hello!
bullet code:
image
how to make it push the bullet in the opposite direction when it hits?

If you make your bullet and enemy both RigidBody2D, they will automatically be bouncing off each other on collision. See my little demo:


This is my scene structure
image

And this is the code on the Player node, adjust it to your needs.

extends CharacterBody2D

@export var speed = 100
@export var gravity = 200
@export var bullet_scene: PackedScene


func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed("click"):
		shoot()


func _physics_process(delta):
	velocity.y += gravity * delta
	horizontal_movement()
	move_and_slide()


func horizontal_movement():
	var horizontal_input = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")
	velocity.x = horizontal_input * speed


func shoot() -> void:
	var bullet: RigidBody2D = bullet_scene.instantiate()
	get_tree().current_scene.add_child(bullet)
	bullet.global_position = self.global_position + Vector2(100.0, 0.0)
	bullet.apply_impulse(Vector2(1000.0, 0.0))
	await get_tree().create_timer(2).timeout
	bullet.queue_free()
1 Like

thanks, but I don’t use area to create enemies and bullets. I do everything through area2D

I managed to make a similar one, but it works very poorly and sometimes pushes in the other direction, I think it’s more like pushing in a random direction than in the direction of the bullet

image

Perhaps you know how to fix this?

I can’t quite understand what you want to achieve with this method.
What is pushing?
What is area?
What is area.get_parent().push?
There is a lot of code here that you’re not showing. Also, you never shared your scene structure.

Nonetheless, is there any specific reason you don’t want to use RigidBody2D and you insist on working with just Area2D? You are trying to reinvent the wheel, which is already provided to you directly by the game engine. As you can see in my example, I could easily achieve the correct (I think) and naturally-looking behavior with just a couple lines of code.

This is the best and simplest solution, thanks for the answer!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.