Bullet moves in direction of mouse, even in midair

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

Hello

I have a problem with the way my bullet moves. After trying many different options, I finally made a bullet that moves and works the way I want it, with one small caveat: even after shooting it, it follows the mouse’s position. I want a bullet that, after being shot, continues in the direction it was originally shot. Here is the code:

Bullet code:

extends Node2D

var pos
var vel = Vector2(0,1000) # Change Y factor to change bullet speed
onready var timer = get_node("Timer")

func _ready():
    set_process(true)
    timer.set_active(false)

func _process(delta):
    pos = get_pos()
    if Input.is_action_pressed("Click"):
  	    timer.set_active(true)
    if timer.is_active():
	    pos += vel*delta
    set_pos(pos)

In the node tree, the bullet is a child of weapon. The weapon’s code allows it to look_at() the local_mouse_position(), so the bullet will fire towards wherever the mouse is at. My question is how to make the bullet shoot straight rather than change in midair according to where the mouse is?

:bust_in_silhouette: Reply From: 2plus2makes5

In my opinion the problem could be that the bullet is child of weapon, if you rotate the weapon all its children will rotate.

I had considered that, but if it is not a child of weapon, then it will not move with weapon when it rotates towards the mouse.

CosmicNerd6505 | 2018-04-07 18:06

It definitely shouldn’t be a child of the weapon. It can be a child of the weapon when not firing, but once fired it should be a child of the highest level scene. You can probably just find the global_position of the mouse click, make the bullet a child of the weapon’s parent scene, and send the bullet in that direction.

Socrates | 2018-04-07 18:31

If i understand correctly you want the bullet to behave like a normal bullet, its direction should always remain the same right?

In my opinion in that case the bullet definitively shouldn’t be child of weapon because it has to be independent from the weapon, at the moment of the creation of the bullet you should pass weapon’s rotation to the bullet and then use move_local_x(speed) instead of translate or set_pos, the bullet should move toward the desired direction.

2plus2makes5 | 2018-04-07 19:03