How to set position of RigidBody2D to the get_viewport().get_mouse_position()?

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

*How to set position of RigidBody2D to the get_viewport().get_mouse_position()?

I’m making a small little sandbox sort of project and I decided I’d start with a StaticBody2D platform at the bottom of the world (which works fine). I am trying to make a script that when the mouse is clicked, it will load the ball.tscn, and then ball.instance() into the world. Then I try to set it’s location to the mousePos variable, which I made as

mousePos = get_viewport().get_mouse_position()

It doesn’t work when I click. I think a few times in my debugging process it DID spawn in, but it always went to 1 spot, it never went to where the mouse is.

This entire script was under the _process(delta) function because I figured you need to always check if they clicked or not and where.

The script was inside of the ball RigidBody2D inside of my game, like this:

extends RigidBody2D

func _process(delta):
var mousePos = get_viewport().get_mouse_position()

var ballScene = load("res://ball.tscn")


print(mousePos)
if Input.is_action_pressed("space"):
	var newBall = ballScene.instance()
	newBall.position = mousePos
	add_child_below_node(get_tree().get_root().get_node("World"), newBall)

As you can see in the script, I resorted to using space because when I was playing with the code to try to fix it, space sometimes did spawn one in, but again, not at the mouse’s position.

Thank you for the help!

I can’t entirely answer your question but I recommend assigning nodes to variables like “World” at the top of your script. That way you can avoid overly complex get_node() calls and just write code as you would read it.
I can’t tell what’s going wrong based just on the code you’ve provided. Can you host your project somewhere?

DDoop | 2020-06-26 20:50

:bust_in_silhouette: Reply From: jgodfrey

Here’s a rough (but working) example. Just season to taste…

var rb = preload("res://RigidBody2D.tscn")

func _input(event):
	if event is InputEventMouseButton and event.is_pressed():
		var rb_inst = rb.instance()
		rb_inst.global_position = event.position
		get_parent().add_child(rb_inst)

The above script should be placed on the scene you want to instance the RigidBody2D-based scene into. In this case, I just add the instanced scene as a sibling of the current scene, so you probably want to change that.

Thank you! Fixed

d6ta | 2020-06-26 23:58