Godot Version
Godot_v4.4.1-stable_win64
Question
Hi,
I am trying to make a top down shooter.
I have two sprites that I want to use depending on where the player looks (up-down or sideways) which is controlled by the mosue pointer. I have treid multiple things but I was not able to find anything that could determine wether the mouse was in one area or not.
Imagine you draw a line from one corner of the screen to the other, creating a cross, with the player in the middle where the lines meet. I want to be able to detect if the mouse is in either of these triangles created by the lines. For example if the mouse is in the right triangle (right part of the screen) The sprite changes. Any ideas?
I asked chatgpt 
I haven’t tried the implementation, but the solution is basically:
- Getting viewport rectangle
- Converting mouse pos to viewport rectangle position (relative to the viewport rect centre)
- Checking which side it is by comparing x and y component of the mouse_pos
extends Node2D
enum TriangleRegion { TOP, BOTTOM, LEFT, RIGHT, NONE }
func get_mouse_triangle() -> TriangleRegion:
var center = get_viewport_rect().size / 2
var mouse_pos = get_viewport().get_mouse_position()
var rel = mouse_pos - center
if rel.y > rel.x and rel.y > -rel.x:
return TriangleRegion.BOTTOM
elif rel.y < rel.x and rel.y < -rel.x:
return TriangleRegion.TOP
elif rel.y > rel.x and rel.y < -rel.x:
return TriangleRegion.LEFT
elif rel.y < rel.x and rel.y > -rel.x:
return TriangleRegion.RIGHT
return TriangleRegion.NONE # fallback (shouldn't happen)
func _process(_delta: float) -> void:
var region = get_mouse_triangle()
match region:
TriangleRegion.TOP:
print("Top")
TriangleRegion.BOTTOM:
print("Bottom")
TriangleRegion.LEFT:
print("Left")
TriangleRegion.RIGHT:
print("Right")
_:
pass