繁体   English   中英

有没有办法在Unity中实现触摸和保持

[英]Is there a way to implement a touch and hold in Unity

当手指放在屏幕上时,有没有办法让事情发生。

我想要做的是将手指放在屏幕上并使对象旋转(仅限 Y 轴),同时手指仍在屏幕上。 当手指抬起时,旋转应停止。

这是我的代码:

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);    
            }
        }
    }
}

我希望对象应该在我的手指(在 PC 上它也可以与鼠标一起使用)在屏幕上时旋转。

会发生什么 - 它只旋转 1 帧然后停止。 它像单击一下一样注册它,我的手指是否仍在屏幕上并不重要。

我很确定我做错了,我只是看不到哪里。


如果你想检测用户是否正在按住鼠标按钮,你应该使用

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

事实上,这行代码即使在移动设备上也能工作,但如果你想使用 Touches,

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

我面临着类似的问题。 如果用户拿着屏幕,我想围绕一个点旋转我的播放器。 向右触摸使玩家顺时针移动,反之亦然。 这是代码:

 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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