I am looking for a sprite (a bullet to be more specific), to come out of another sprite (the end of the gun) by clicking the left mouse button, and then have the bullet go in the direction of where the mouse was, and then not change position after the click happens. I explained it pretty badly, but basically I'm looking for the bullet to go to the direction of the mouse, and once clicked, to not change position and follow to that direction till it goes off the screen. A good example of what I am trying to do is how shooting and bullets work in a game called Terraria.
I've been trying to figure it out using a Position2D. I have the Position2D at the end of the gun, where I want the bullet to load in. I've tried researching through google and Youtube as well. Right now I have a sprite (an arm) that rotates depending on the mouse position, and a sprite (the gun) attached to the arm. I am trying to use the arm information to find the direction, but I am unable to figure it out. I am a beginner with coding in general.
This is the code for my arm that rotates depending on mouse position:
extends Sprite
var Mouse_Position
func _process(delta):
Mouse_Position = get_local_mouse_position()
rotation += Mouse_Position.angle()*0.2
The code currently for my bullet is:
extends Area2D
const SPEED = 100
var velocity = Vector2()
var Mouse_Position
func _physics_process(delta):
velocity.x = SPEED * delta
Mouse_Position = get_local_mouse_position()
rotation += Mouse_Position.angle()*0.2
translate(velocity)
func _on_VisibilityNotifier2D_screen_exited():
queue_free()
Also here some extra for loading it in:
const BULLET = preload("res://Bullet.tscn")
if Input.is_action_just_pressed("shoot"):
var bullet = BULLET.instance()
get_parent().add_child(bullet)
bullet.position = $Position2D.global_position
