Hello, I’m currently working on a little tank game, and I’d like the tank’s projectiles to be able to bounce off of walls. While setting up the tank functionality I made a simple bullet scene for the tank to shoot out, but the bullet uses an Area2D and now that I’d like to implement the bounce mechanic I’ve realized that an Area2D isn’t really fit for that, and I should probably use a CharacterBody2D instead, since it has a built in bounce function. I can get a projectile to bounce off of walls, but I can’t for the life of me get that projectile to spawn in front of the tank and to shoot towards where it’s turret is pointed/where the mouse cursor is. Any help would be greatly appreciated! Here’s the basic code I’ve written so far.
#Bullet Script
extends Area2D
@export var speed = 300
func _physics_process(delta):
position += transform.x * speed * delta
func _on_timer_timeout():
queue_free()
SignalBus.bullet_removed.emit()
#Part of the player script that controls shooting
func shoot():
var bullet = bullet_scene.instantiate()
owner.add_child(bullet)
bullet.transform = marker_2d.global_transform
You need to set the global position for the object you are spawning. That position needs to be modified by the angle the turret is pointing at, with an offset so it doesn’t spawn on top of the tank.
owner probably shouldn’t be used, as I understand it the property is more intended for editor plugins and creating PackedScenes. You could use add_sibling to add the bullet alongside the player in the scene tree, then you can copy the global transform over.
CharacterBody2D doesn’t have a bounce function, Vectors do, including Vector2. However using bounce with a CharacterBody2D will be much easier, as CharacterBody2D’s move_and_collide handles both moving the object and detecting the exact collision stopping point, and collision normal required for .bounce to work.
Thanks for the feedback! I changed the bullet script to this, and I can get the bullet to spawn in front of the turret, but I’m still struggling to get it to move forward. This is the bullet script I have now:
extends CharacterBody2D
@export var speed = 300
func _physics_process(delta):
var collision = move_and_collide(velocity * delta)
if collision:
velocity = velocity.bounce(collision.get_normal())
Obviously I need to code the bullet to actually move, but everything I’ve tried hasn’t worked so far, best I got was the bullet moving forward but then sliding along a wall instead of bouncing away from it. Sorry if this is a dumb question (-_-)
If you want to do it in a more controlled manner see the other people’s great suggestions. Otherwise if it just has to bounce you can use a rigid body and make it bouncy + code to kill it when neccessary