0
votes

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
1

1 Answers

1
votes

You need to set a variable for the direction before the instance and not change it when the _process function is called:

Something like this:

extends Area2D

const SPEED = 100
var velocity = Vector2()
export (int) var dir # <--- Add this variable to modify the direction of the bullet from outside of the scene
var Mouse_Position


func _physics_process(delta):
   $Sprite.position += Vector2(SPEED * delta, 0.0).rotated(dir)
   $Sprite.global_rotation = dir  # Set the rotation of the Bullet


func _on_VisibilityNotifier2D_screen_exited():
    queue_free()

And when you're instancing the bullet:

var bullet = BULLET.instance()
bullet.dir = $Sprite.global_rotation # <-- Assgin the rotation of the player to the bullet
get_parent().add_child(bullet)
bullet.position = $Sprite/Position2D.global_position # <-- Start the Bullet on the position2D

The result :

enter image description here