0 votes

**How to set position of RigidBody2D to the getviewport().getmouse_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().getmouseposition()

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!

in Engine by (20 points)

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?

1 Answer

0 votes
Best answer

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.

by (8,856 points)
selected by

Thank you! Fixed

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.

Categories