0
\$\begingroup\$

I want to implement a feature in my mobile game where if you press on a game object for a certain amount of time while not moving your finger an animation will play. I also need to be able to drag and drop objects. I have the drag and drop functionality working already, but know I also need the press and hold feature. I have this code at the moment:

 private void Update()
 {
    foreach (var touch in Touch.activeTouches)
    {
        // Only respond to first finger
        if (touch.finger.index == 0 && touch.isInProgress)
        {
            Ray ray = mainCamera.ScreenPointToRay(touch.screenPosition);

            RaycastHit2D hit = Physics2D.GetRayIntersection(ray);

            if (hit.collider != null)
            {
                print("Selected: " + hit.collider.name);
                // Drag game object
            }

        }
    }
}

This code works just like I want it. You put a finger on the screen and a ray is used to select an object that I can drag. But I am not sure where to start on the other feature described in the paragraph above, there is a startTime and a startScreenPosition property that maybe can be used for this, but I don't know how. Any help is greatly appreciated.

Thanks.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

A couple of notes: Unless you specifically want to check that the user keeps their finger on the desired object at all times, I would probably only check at the beginning of the touch, as well as the moment when you want the hold to trigger.

You can simply compare the startTime property to Time.realTimeSinceStartup and check when a certain amount of time has passed. You then just need to take care of only calling a method or performing some action once!

private const float HoldTime = 0.5f;
private bool _triggeredHold = false;

private void Update()
{   
    foreach (var touch in Touch.activeTouches)
    {
        if (touch.finger.index == 0 && touch.began)
        {
            _triggeredHold = false;
        }

        // Only respond to first finger
        if (touch.finger.index == 0 && touch.isInProgress)
        {
            var delta = Time.realTimeSinceStartup - touch.startTime;  

            if (delta > HoldTime && _triggeredHold == false)
            {
                _triggeredHold = true;
                
                // Do something
            }

            // ...
        }
    }
}
```
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .