Last active
July 5, 2017 13:34
-
-
Save willnationsdev/2c7c501b6dfe34fcd83af8f84c1c46b6 to your computer and use it in GitHub Desktop.
HoverContainer: emits a "mouse_hovering" event periodically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Container | |
signal mouse_hovering(position, velocity) | |
var is_hovering = false | |
export var hover_emission_rate = 1.0 | |
var hover_accumulator = 0.0 | |
var last_mouse_position = Vector2(0,0) | |
func _ready(): | |
connect("mouse_entered", self, "on_mouse_entered") | |
connect("mouse_exited", self, "on_mouse_exited") | |
# Godot 2.1.x: connect("mouse_enter", self, "on_mouse_entered") | |
# Godot 2.1.x: connect("mouse_exit", self, "on_mouse_exited") | |
connect("mouse_hovering", self, "on_mouse_hovering") | |
set_fixed_process(true) | |
func _fixed_process(delta): | |
hover_accumulator += delta | |
if is_hovering && hover_accumulator >= hover_emission_rate: | |
# Needed because Input.get_(last_)mouse_speed() does not update when not moving between frames. | |
# Ergo, a steady mouse will not return Vector2(0,0). | |
var true_speed = Vector2(0,0) | |
# if we changed position | |
if get_viewport().get_mouse_position() != last_mouse_position: | |
# Godot 2.1.x: if get_viewport().get_mouse_pos() != last_mouse_position: | |
# then grab the latest mouse velocity | |
true_speed = Input.get_last_mouse_speed() | |
# Godot 2.1.x: true_speed = Input.get_mouse_speed() | |
# Regardless, update the last known mouse position | |
last_mouse_position = get_viewport().get_mouse_position() | |
emit_signal("mouse_hovering", last_mouse_position, true_speed) | |
while hover_accumulator >= hover_emission_rate: | |
hover_accumulator -= hover_emission_rate | |
func on_mouse_hovering(p_mouse_position, p_mouse_speed): | |
print("hovering at position " + str(p_mouse_position) + " with velocity " + str(p_mouse_speed)) | |
func on_mouse_entered(): | |
is_hovering = true | |
func on_mouse_exited(): | |
is_hovering = false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment