+1 vote

Just started using Godot engine yesterday and I'm liking the way it works. I'm trying to make a 2D Megaman-esque game with all the platforming & shooting. After using some tutorials, I found a way to spawn a scene (in this case, an image of an animated water bolt with collision) at the origin using this code:

const WATER_BOLT = preload("WaterBolt.tscn")
    if Input.is_action_just_pressed("ui_focus_next"):
        var waterbolt = WATER_BOLT.instance()
        get_parent().add_child(waterbolt)

After using this code and finding it works, I added the next line, to spawn it at the Position2D node I had set up in the player scene:

    waterbolt.position = $Position2D.global_position

This is where things broke. The game would freeze up, and the output would give me the error:

Invalid set index 'position' (on base: 'Node') with value of type
'Vector2'

I've searched up a couple of tutorials on projectile spawned, and did some error searching, to no avail.

This is the original tutorial, linked to where the guy adds the lines of code similar to what I did: https://youtu.be/wRcGbQBq28c?t=663

I don't know what to do here, the tutorial seems recent enough, and I don't see any specific typos that would cause the error. Please try to help me with my issue.

Thanks!

in Engine by (13 points)

1 Answer

+3 votes

From the error, your scene seems to be a Node and that class does not have position.

Also it does not freeze, the executions breaks on error (probably pointing you to the line with the problem).


To fix that, change the root of the WaterBolt.tscn to be a Node2D (you can change the node type wit right click), save it and now it does have a position property.

ps: be careful on when and how do you set the position, if doing it before adding the scene to the tree, it will be a global, if you set it after entering the tree the new position will be relative to the parent's position (if the parent has a transform).

by (7,860 points)

Thank you so much! This fixed the problem.
Didn't know that the parent node I had everything under was supposed to be a Node2D, I'll keep this in mind from now on.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.