Should I program everything in root node or separate code into child node?

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

Hey guys, I have a gun node as the root node (it is a kinematics node) and a child node which is a bullet (also a kinematics node) is attatched to the gun node.

Now when I press space to shoot, then the bullet should come out. So how should I go about doing this.

Should I make the bullet invisible (by toggling the visibility as off)?

Should I program this space shooting script on the gun or on the bullet?

:bust_in_silhouette: Reply From: Inces

I don’t think You want to have bullet as a child of gun. Child always copy transform of a parent, and that would make your bullet change trajectory when You move a gun. Good practice is to instance() a new bullet from a script in a gun. If bullet has no additional behaviors, You can also set its speed and direction from a gun script. However if You want bullet to behave differently based on events happening after the moment of shooting - You should also script the bullet in a way it handles his own trajectory.

Ok so currently the bullet has movement which works fine.

So in the gun script I use instance() and how do I exactly get the bullet to spawn where the gun is?

Joe0239 | 2022-02-11 12:29

by manually setting its position to position of a gun, like :

bullet.global_position = gun.global_position 


bullet.global_transform = gun.global_transform

in order to instance() a bullet You need to load/preload it first, and than instance() the result, like

var bullet = preload("res://bullet.tscn")
var bulletinst = bullet.instance()

Inces | 2022-02-11 14:39

Hey mate, but why do I need this:

var bulletinst = bullet.instance() when in your example I never end up using the bulletinst variable?

Joe0239 | 2022-02-13 00:21

var bullet = preload("res://bullet.tscn") 

first You you change the path to resource ( like take a blueprint of a scene)

var bulletinst = bullet.instance()

next You create individual object using this blieprint.

 bulletinst.global_postition = gun.global_position

finally You set any variable to this individual object

Generally You always have to call a blueprint once, and than instance() this blueprint as many times as many bullets You want

Inces | 2022-02-13 01:17

:bust_in_silhouette: Reply From: ReudsFratt92

I would create a bullets:Node in level hierarchy and add every new bullet there. Then you can access any or every bullet, because they kinda are in a folder

onready var bullet = preload("path to bullet.tscn")

gun creates an instance of bullet

newbullet = bullet.instance()

maybe sets bullet’s varibles

newbullet.speed = 10

and since then bullet is on it’s own

The bullet node won’t be a child to the gun node, right?

Joe0239 | 2022-02-11 12:27