|
|
|
 |
Reply From: |
Tom Mertz |
There are a couple different ways to do this from what I could find.
The Area2D inherits from CollisionObject2D which has the signal mouse_entered
From the docs:
Emitted when the mouse pointer enters any of this object’s shapes. Requires input_pickable to be true and at least one collision_layer bit to be set.
So make sure you set your input_pickable to on in the inspector and have a collision layer selection.
Check out the docs on how to setup signals.
For me, I was doing the checking on the mouse every frame and didn’t want to have to connect my objects I was creating at run time, so on my master mouse script I used the Physics2DDirectSpaceState
’s method intersect_point:
func _physics_process(delta):
# get the Physics2DDirectSpaceState object
var space = get_world_2d().direct_space_state
# Get the mouse's position
var mousePos = get_global_mouse_position()
# Check if there is a collision at the mouse position
if space.intersect_point(mousePos, 1):
print("hit something")
else:
print("no hit")
It’s worth noting that the above code checks for Rigidbodies by default, if you need to check for Areas, you’ll need to use some like
if space.intersect_point(mousePos, 1, [], 2147483647, true, true):
The docs on the intersect_point method give more info on what all the params are, but the last true is the most important for Area2D checking.
Update
The get_global_mouse_position
method is only available on a CanvasItem and all its subclasses. So, any subclass of Control and Node2D. If your script is extending a regular Node. You can use the method from NatGazer below to get the mouse position:
var mousePos = get_viewport().get_mouse_position()
I had to use this to get mouse position in Godot 4.0.2:
var mousePos = get_viewport().get_mouse_position()
NatGazer | 2023-05-09 14:46
Are you sure your script has a extends at the top that is CanvasItem or above? Node2D and Control (and all of their subclasses) both inherit from CanvasItem so they both have access to the get_global_mouse_position method. If your script had just extends Node
you wouldn’t have access to that method. Your way it totally fine though if your script/scene isn’t a Node2D or Control. But it’s possible you could also change your extends and it’d work.
Tom Mertz | 2023-05-16 00:56