首页 > 解决方案 > 如何更改以下 Unity C# 游戏对象左/右滑动代码以进行鼠标单击?

问题描述

我想在 Unity 编辑器上测试游戏,这就是为什么我想更改鼠标单击的以下代码,因为“触摸”在统一编辑器中不起作用。我每次都必须制作一个APK来测试游戏。请帮我解决一下这个。

float swipespeed = 0.002f;
void Update 
{
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        // Get movement of the finger since last frame
        Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
        float pos=touchDeltaPosition.x;
        // Move object across XY plane
        transform.Translate( 0f,0f,-pos * swipespeed);
    }
}

标签: c#unity3d

解决方案


假设其余部分按您的需要工作,您可以检查Input.mousePresent

指示是否检测到鼠标设备。

在 Windows、Android 和 Metro 平台上,此函数执行实际的鼠标存在检测,因此可能返回 true 或 false。在 Linux、Mac、WebGL 上,此函数将始终返回 true。在 iOS 和控制台平台上,此函数将始终返回 false。

或者也可以Input.touchSupported

返回当前运行应用程序的设备是否支持触摸输入。

无需检查平台,而是使用此属性来确定您的游戏是否应该期待触摸输入,因为某些平台可以支持多种输入法。

并做类似的事情

public float swipeSpeed = 0.002f;

// Here every frame the last mousePosition will be stored
// so we can compare the current one against it
private Vector3 lastMousePos;

private void Update 
{
    if(Input.mousePresent)
    {
        if(Input.GetMouseButton(0))
        {
            var currentMousePos = Input.mousePosition;
            var mouseDeltaPosition = currentMousePos - lastMousePos;

            transform.Translate( 0f,0f, -mouseDeltaPosition.x * swipespeed);
        }

        // update the last position with the current
        lastMousePos = currentMousePos;
    }
    else
    {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            // Get movement of the finger since last frame
            var touchDeltaPosition = Input.GetTouch(0).deltaPosition;

            // Move object across XY plane
            transform.Translate( 0f,0f, -touchDeltaPosition.x * swipespeed);
        }
    }
}

推荐阅读