35 lines
1.4 KiB
GDScript3
35 lines
1.4 KiB
GDScript3
|
|
extends Area3D
|
||
|
|
|
||
|
|
@onready var viewport: SubViewport = %SubViewport
|
||
|
|
@onready var screen_mesh: MeshInstance3D = $".."
|
||
|
|
|
||
|
|
func _input_event(_camera: Camera3D, event: InputEvent, event_position: Vector3, _normal: Vector3, _shape_idx: int) -> void:
|
||
|
|
# Only care about mouse/touch events
|
||
|
|
if not (event is InputEventMouse or event is InputEventScreenTouch):
|
||
|
|
return
|
||
|
|
|
||
|
|
# 1. Convert the world 3D click into local 3D coordinates relative to the ScreenMesh
|
||
|
|
var local_pos = screen_mesh.to_local(event_position)
|
||
|
|
|
||
|
|
# 2. Get the size of our 3D QuadMesh
|
||
|
|
var quad_size = screen_mesh.mesh.size
|
||
|
|
|
||
|
|
# 3. Convert the local 3D position into a 2D percentage (0.0 to 1.0)
|
||
|
|
# (Quad coordinates go from -0.5 to +0.5 from the center. We offset by +0.5 to make it 0 to 1)
|
||
|
|
var percent_x = (local_pos.x / quad_size.x) + 0.5
|
||
|
|
|
||
|
|
# 3D Y goes UP. 2D Y goes DOWN. We must invert the Y axis!
|
||
|
|
var percent_y = 0.5 - (local_pos.y / quad_size.y)
|
||
|
|
|
||
|
|
# 4. Multiply the percentage by the SubViewport's actual pixel resolution
|
||
|
|
var viewport_size = viewport.size
|
||
|
|
var final_2d_pos = Vector2(percent_x * viewport_size.x, percent_y * viewport_size.y)
|
||
|
|
|
||
|
|
# 5. Overwrite the event's position data with our calculated 2D coordinates
|
||
|
|
event.position = final_2d_pos
|
||
|
|
if event is InputEventMouse:
|
||
|
|
event.global_position = final_2d_pos
|
||
|
|
|
||
|
|
# 6. Force the SubViewport to process this customized 2D event!
|
||
|
|
viewport.push_input(event)
|