Making bullets shoot towards mouse

Godot Version

Godot 4.2.1 stable

Question

How do I create a gun that shoots towards the mouse?

if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT) and can_fire == true:
		var bullet_instance = bullet.instantiate()
		bullet_instance.position = $RayCast2D/Sprite2D/Marker2D.position
		bullet_instance.rotation_degrees = $RayCast2D.rotation_degrees
		bullet_instance.rot_angle = $RayCast2D.rotation
		bullet_instance.apply_impulse(Vector2() , Vector2(b_speed , 0).rotated($RayCast2D.rotation))
		can_fire == false
		await get_tree().create_timer(fire_rate).timeout
		can_fire = true

My code is right here. I have followed 3 tutorials and one of them got me to this, where when I press shoot the bullets fly out for a second then stop midair and keep aiming towards my mouse. it also says can_fire = false doesn’t do anything.

if I jump into them they start floating away and still follow my mouse

Seems like the rotation is based on the RayCast2D node, do you want the RayCast to also rotate toward the mouse? If so try using look_at on said node

func _process(delta: float) -> void:
    $RayCast2D.look_at(get_global_mouse_position())

sorry I didn’t show that in the script but its there just above it. the main problem is it just wont shoot

you need to add the bullets to the scene tree somehow, try add_sibling

if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT) and can_fire == true:
		var bullet_instance = bullet.instantiate()
		bullet_instance.position = $RayCast2D/Sprite2D/Marker2D.position
		bullet_instance.rotation_degrees = $RayCast2D.rotation_degrees
		bullet_instance.rot_angle = $RayCast2D.rotation
		bullet_instance.apply_impulse(Vector2() , Vector2(b_speed , 0).rotated($RayCast2D.rotation))

		add_sibling(bullet_instance) # << add_child or add_sibling

		can_fire == false
		await get_tree().create_timer(fire_rate).timeout
		can_fire = true

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