Godot Version
4.4.1
Question
Trying to run code to create a knob in a 2D scene, but when attempting to run the scene I get an error on a line attempting to gain the global mouse position. Code looks like this:
extends Node2D
@export var maxDist: int = 100
var following := false
func _ready():
Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
func _physics_process(_delta: float):
var mouseDistance := get_global_mouse_position().distance_squared_to($knob.global_position)
if mouseDistance < maxDist and Input.is_action_just_pressed("click"):
following = true
if Input.is_action_just_released("click"):
following = false
print(following)
I thought a line of Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
was causing an error but the error persited after commenting the line in question, any clue what is causing this?
Based on the code provided, you don’t reference $knob
anywhere in your code. You should first get a reference to it before trying to access it, see:
The code is appended to a Node2D “Knob” that has as a child node a 2D marker “knob”, maybe I just don’t understand child nodes that well but I thought since “knob” is a child of “Knob” that it would be callable via code?
It should work.
Can you share the error you’re getting?
EDIT: oh sorry, didn’t realize it was in the thread title.
Then, try to export the knob as a Node2D variable and reference it manually instead of getting it using the $
sign. I don’t see why it would work better, but it’s worth a try!
You need to first reference the node you are trying to use. The best way would be to do it in a similar way you did with maxDist.
@export var knob: Knob
Then you should do:
knob.global_position
Without the $
character.
This also assumes that “knob” has the class_name of “Knob” but if it’s different, use that.
If it’s just a simple Node2D, then do:
@export var knob: Node2D
After you do this, make sure that you set the reference inside the editor like you would with maxDist
you already did.