Swipe throw mechanism, that works with both mouse and touchscreen?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Footurist

How do you accomplish a good swipe throw mechanism (in this case to swipe a bar of buttons)? I tried

var last_speed
var thrown = false

func _input(event):
    if event is InputEventScreenDrag:
        last_speed = event.speed
    if event is InputEventScreenTouch and not event.is_pressed():
        thrown = true

func _process(delta):
    if thrown:
        object.translate(last_speed)

But the speed will always be too slow or reverse, because you stop the mouse or touch movement too early…Any ideas?

:bust_in_silhouette: Reply From: pgregory

I use something similar to this for Fruit Spritzer, a match 3 game that uses swipes. I’m mainly interested in the direction of the swipe, not the speed, but I’ve added some code that should be able to provide you the right information, swiping is confirmed to work on desktop and iOS/Android, timing/speed not tested, but should point you in the right direction.

var elapsed_time = 0    
var start
var speed
var start_time
var direction

func _input(event):
	if event is InputEventMouseButton:
		if event.is_pressed():
			start = event.position
			start_time = elapsed_time
		else:
			direction = event.position - start
			speed = (direction.length())/(elapsed_time - start_time)
			direction = direction.normalized()
			print(direction, speed)

func _process(delta):
	elapsed_time += delta

I can tell by just looking at it, that’s it! I was stuck with the speed property of the InputEventScreenDrag, which will of course be too slow at the end of the mouse movement, because of how the human hand controls it. Thanks a lot!

Footurist | 2018-03-03 07:07

It’s helpful for me. I’ve extended it a little and append a time period after which the swipe info will be send, which allows to track moving until mouse pressed.

rojekabc | 2021-07-15 09:21