So, I created a gun which reacts to my right stick :
extends Node2D
var shot = preload( "res://tscn/weapons/shot.tscn" )
var RS_x = 0
var RS_y = 0
func _ready():
set_fixed_process( true )
func _fixed_process( delta ):
RS_x = Input.get_joy_axis(0, 2)
RS_y = Input.get_joy_axis(0, 3)
if RS_x > 0.5 || RS_x < - 0.5 || RS_y > 0.5 || RS_y < - 0.5:
_shoot_bullet( RS_x, RS_y )
func _shoot_bullet( RS_x, RS_y ):
var new_shot = shot.instance()
new_shot.set_global_pos( get_node( "shootfrom" ).get_global_pos() )
new_shot._set_direction( Vector2( RS_x, RS_y ) )
get_node("../..").add_child( new_shot )
It adds a shot, passing the stick direction as argument to this function (inside the "shot" node) :
func _set_direction( vector ):
direction = vector
direction = direction.normalized()
direction_set = true
Everything works fine, and once inside the tree, the shot goes to the same direction until it's freed. That's what I want.
I then created an enemy, JackBot, which locates the player every frame and shoots him when he can :
extends Area2D
var shot = preload( "res://tscn/weapons/enemy_shot.tscn" )
var shoot_decay = 0.2
var time_since_shoot = 0
var shoot_direction
func _ready():
set_fixed_process( true )
func _fixed_process(delta):
_locate_player()
if time_since_shoot < shoot_decay:
time_since_shoot += delta
else:
time_since_shoot = 0
_shoot_bullet( shoot_direction )
func _locate_player():
shoot_direction = - ( get_node("shootfrom").get_global_pos() - get_node("../../player/target").get_global_pos() )
func _shoot_bullet( shoot_direction ):
var new_shot = shot.instance()
new_shot.set_global_pos( get_node( "shootfrom" ).get_global_pos() )
new_shot._set_direction( shoot_direction )
get_node("../..").add_child( new_shot )
I copied the _set_direction(): function from shot to enemy_shot (the node JackBot adds when he shoots). But instead of going straight in a line, the shot now follows the player, as if the vector argument was a pointer to the constantly updated shoot_direction variable, which tracks the position of the player.
So here are my two questions :
How do I copy the shoot_direction Vector2; so once it's passed to the enemy_shot, it remains the same Vector2 (and doesn't point anymore to the player's location) ?
And most important, why the shot instance doesn't change when I move the stick after it has been fired ?
Thanks a lot, please tell me if I did wrong formatting as it's my first question.