简体   繁体   中英

Is there a way to implement a touch and hold in Unity

Is there a way to make something happen while a finger is being held on the screen.

What I'm trying to do is hold my finger on the screen and make an object rotate(Y axis only), while the finger is still on the screen. The rotation should stop when the finger is lifted.

Here is my code:

using UnityEngine;

public class RotateObs : MonoBehaviour
{
    public float rotateSpeed;

    private void Update()
    {
        if(Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            if (touch.phase == TouchPhase.Began)
            {
                transform.Rotate(Vector3.up * rotateSpeed * Time.deltaTime);    
            }
        }
    }
}

I expect the object should be rotating while my finger(on PC it works with mouse too) is on the screen.

What happens is - it rotates for 1 frame only and then stops. It registers it like it's a single tap, it doesn't matter if my finger is still on the screen or not.

I'm pretty sure I'm doing it wrong, I just can't see where.


If you want to detect if the user is holding the mouse button, you should use

if (Input.GetMouseButton(0))
{
    transform.Rotate (Vector3.up * rotateSpeed * Time.deltaTime);
}

In fact, this line of code will work even in mobile, but in case if you want to work with Touches,

if (Input.touchCount > 0)
{
    Touch first = Input.GetTouch (0);
    if (first.phase == TouchPhase.Stationary) 
    {
        transform.Rotate (Vector3.up * rotateSpeed * Time.deltaTime);
    }
}

I was facing a similar problem . I wanted to rotate my player around a point if the user was holding the screen . Touch to the right moves the player clockwise and vice versa. Here's the code :

 void Update()
{
    if(Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
        Vector3 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
        touchPos.z = 0f;
        if (touch.phase == TouchPhase.Stationary)
        {
            if (touchPos.x > 0)
                movement = 1f;
            else if (touchPos.x < 0)
                movement = -1f;
        }
        if (touch.phase == TouchPhase.Ended)
        {
            movement = 0f;
        }
        
    }
}

private void FixedUpdate()
{
    transform.RotateAround(centre, Vector3.forward, movement * Time.fixedDeltaTime * -moveSpeed);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM