0 votes

Hello,

I am trying to figure out how Gd scripting works. Am trying to instance a Scene called Ball via script.

I have a main scene where I want to instance another scene called Ball.

enter image description here

And Ball scene:
enter image description here

In Main scene I have the script:

    extends Node2D

func _ready():
    set_process_input(true)

func _input(event):
    var Ball_asset = get_tree().get_root().get_node("/root/Graphics/Ball")
    if (event.type==InputEvent.MOUSE_BUTTON):
        add_child(Ball_asset).Mouse_position(event.pos)

When I run it. The ball falls and bounces on the collisionShape, but when I press mouse button it freezes and gives me this error: Invalid call. Nonexistent function 'Mouse_position' in base 'Nil'.

Been looking at the documentation and example projects. But I would appreciate some advice on what I am missing.

Thanks
4k4deusz

in Engine by (29 points)

3 Answers

+1 vote

You are looking for /root/Graphics/Ball when in your scene I see /root/Main/StaticBody2D/Ball.

Also You have a rigid body as child of a static body.

I know is boring but I suggest you to read all the official docs and tutorials about scenes, scene tree, instancing, Input and InputEvents and Physics.

by (7,894 points)

Thanks for pointing out my mistakes. I dont find reading the official docs boring, but I did miss the Input and InputEvents section for some unknown reason.

+1 vote

What's

add_child(Ball_asset).Mouse_position(event.pos)

?
That Mouse_position function doesn't exist, and that's exactly what the error is telling you: that function doesn't exist. You want to do:

var new_ball = add_child(Ball_asset)
new_ball.set_pos(event.pos)
by (25 points)

Thanks for the example. Really helps. I miss more examples when reading the otherwise fine official docs.

+1 vote

Try instancing the ball scene and adding it at the mouse click coordinates:

extends Node2D

#use correct file extension for Ball scene (tscn, scn, xml, etc.)
var Ball_asset = preload("res://graphics/Ball.tscn")

func _ready():
    set_process_input(true)

func _input(event):
    var new_ball = Ball_asset.instance()
    if (event.type==InputEvent.MOUSE_BUTTON):
        new_ball.set_pos(event.pos)
        add_child(new_ball)
by (1,316 points)

Really appreciate your example, cheers.

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.