Attention | Topic was automatically imported from the old Question2Answer platform. | |
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