Problem instancing a node when pressing mousebutton

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By 4K4deusz
:warning: Old Version Published before Godot 3 was released.

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.

And Ball scene:

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

:bust_in_silhouette: Reply From: eons

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.

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.

4K4deusz | 2016-10-20 18:36

:bust_in_silhouette: Reply From: hipi

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)

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

4K4deusz | 2016-10-20 18:38

:bust_in_silhouette: Reply From: ericdl

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)

Really appreciate your example, cheers.

4K4deusz | 2016-10-20 18:38