Godot 4 top down shooter

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Gre3nboy

I am trying to make a 2d top down shooter game in godot 4 and I can’t figure out the shooting system . The system needs to be: when I click the left mouse button, a instance of a bullet scene needs to spawn at the position of the player and shoot towards the direction of the mouse

I can’t find any tutorial/forum posts on this topic pls help

Godot version: Godot 4.0.1

:bust_in_silhouette: Reply From: crossbito

Hi! I do this in an Area2D(the bullet) :

func _process(delta):
    var forward_direction = Vector2(0, -1).rotated(rotation)
    position += forward_direction * speed * delta

The rotation represents the rotation of the bullet, while speed represents its velocity. The bullet moves forward in the direction it is rotated. When creating the bullet (when someone shoots), I rotate it in the direction the shooter is looking.

Then, in the player or weapon, on click, you can create the bullet. For example(“click” it’s a cutsom input):

func _process(delta):
	if Input.is_action_just_pressed("click"):
		var new_bullet = bullet.duplicate()

		new_bullet.rotation = global_rotation
		new_bullet.global_position=global_position
		new_bullet.visible=true;
		get_tree().root.add_child(new_bullet)

thanks but 1 thing in the player script :

var new_bullet = bullet.instantiate() new_bullet.rotation = global_rotation +1.55 new_bullet.global_position=global_position new_bullet.visible=true; get_tree().root.add_child(new_bullet)

so there was a 90 degree offset in the direction, add 1.55 fixed it. add i instead of using duplicate use instantiate().

Gre3nboy | 2023-06-10 06:12

Ah, yes, I have my character rotated in relation to my weapon. Sorry

crossbito | 2023-06-10 06:20

And I use duplicates because I already have the bullet in the scene and don’t use packages. (Because my game has canyons and things like that where you already have the bullet, I deleted things in the code I pasted.) That’s something I forgot to mention. Maybe this comment would be helpful to someone.

crossbito | 2023-06-10 06:30