[Beginner] Setting vectors for instances separately

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


I’m new to Godot and I stumbled upon a problem, and can’t find simple answer to this. Also I’d like an explanation rather than code so I’d understand this matter. So I’m trying to make a game in which you shoot missiles from bottom of screen to the place where you touch (rest doensn’t matter right now). I made main scene and rocket scene. Main has Position2D node. So when I clicked on screen it spawns rocket in this place (rocket scene is preloaded in main). And here’s my question - how I set vector pointing to place clicked/touched to each instance? Previously I was getting vector in main and then passing to rocket script (which had only position changed in process). But that changed vector of all (now it is obvious to me why). So how you’d do this? Rockets won’t interact with anything, so RigidBody2D seems to be an overkill, they needs just to go to point and spawn explosion (at this point not yet existing). And I’m not posting code for 2 reasons: for now I’m away from my PC and there’s next to no code.

And thank you for any help :slight_smile: and I hope I explained matter well (English is not my native language :p)

:bust_in_silhouette: Reply From: Diet Estus

You can write a custom init() method in your Rocket class which uses a position vector argument to set the position of the rocket.

Unlike, say, Python, you can’t write an argument-taking init() that is automatically called on instancing, so you’ll have to instance your node in main, add it to the scene, and manually call the init() method yourself. (This is my least favorite aspect of Godot, but it’s a small blemish on an otherwise great language.)

Here is the pseudo-code.

In Rocket node:

# custom init manually called when Rockets are instanced 
func init(pos_arg):
    position = pos_arg

In Main node:

# create Rocket
var rocket = load("res://Rocket.tscn").instance() # instance rocket
get_node("/root/.../main_node").add_child(rocket) # add it to scene
rocket_pos = Vector2(32, 64) # replace with dynamic code
rocket.init(rocket_pos) # this sets the rocket's position 

You can even wrap up this code from Main into a function called spawn_rocket(pos_arg) that takes a position as an argument and which spawns a rocket at that position.

While I meant a bit different thing (setting vector not position) the usage of init() was actually what I needed, thank you :smiley: Now it works! And while I’m new, I might still ask a thing or two. So thank you and to the next time :slight_smile:

Wielblad | 2018-04-16 21:08