#I need help with spawning projectile

11 messages · Page 1 of 1 (latest)

hushed jasper
#

Hi i am a beginner , i wanted to make a 2d shooter that have multiple weapons and difference types of projectile .
What i am trying to do now is instantiate a projectile then set the variables for the projectile using resources after (like in the code).
I feels like this is a very un-optimized way of doing this , because i instantiate a new projectile then set the data every times the player shoot.
Is there any better way to implement this ? Thanks for the help

unborn shale
#

Hey! I am a beginner myself so this might not be the best way.

You could try to set up a basic Projectile node tree (as some sort of prefab) and let other inherit these attributes and instanciate them instead.

You can, in your projectile code, do class_name Projectile and then "extends Projectile" instead of extends Node2D, Area2D or whatever.

So basically:
Create a projectile prefab node tree
Copy it
Make it more specific in the code
Inherit (extend) from base projectile class
Instanciate the specific projectile

visual nova
#

the problem with your code is that you are instantiating the class of the Projectile it looks like

#

instantiate() is for PackedScene. So you need to create a PackedScene of you projectile and load it in a variable that you can then instantiate

#

in case you are not familiar with the concept, PackedScene is when you save your node as a scene.
You can reference by either preloading the path

@onready var projectile_template:PackedScene = preload("res//scenes/projectile_template.tscn") )

or exposing the variable so that you can drag and drop the scene in the inspector

@export var projectile_template:PackedScene

hushed jasper
hushed jasper
visual nova
#

I would avoid the name repetition then. Might cause you problems in the future.
Godot's guidelines advise to use snake_case for variables btw

#

(and you can remove the "pass" after your code)

hushed jasper
visual nova
#

and about your actual question, there is nothing wrong with your approach. Worry about optimizing if it starts giving you trouble. The instantiation of the projectile is probably the slowest part (unless you have an enormous amount of data to set to it) which can be improved with pooling.