Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我的触摸算法正确吗?_C#_Unity3d - Fatal编程技术网

C# 我的触摸算法正确吗?

C# 我的触摸算法正确吗?,c#,unity3d,C#,Unity3d,嗨,偷看! 我正在制作一款手机视频游戏,我的触摸移动系统有问题。以下是我希望它的工作方式: 1) 仅在X轴上移动(此处不是问题) 2) 当我按下屏幕时,物体不应该在手指的位置上移动 3) 项目应实时从对象的初始位置移动到对象的当前位置,无需远程传送。 我计算对象的当前位置,如下所示: 对象的当前位置=对象的当前位置+手指的当前位置-手指的初始位置 这是我到目前为止得到的 if (Input.touchCount > 0) { Tou

嗨,偷看! 我正在制作一款手机视频游戏,我的触摸移动系统有问题。以下是我希望它的工作方式:

1) 仅在X轴上移动(此处不是问题)

2) 当我按下屏幕时,物体不应该在手指的位置上移动

3) 项目应实时从对象的初始位置移动到对象的当前位置,无需远程传送。 我计算对象的当前位置,如下所示:

对象的当前位置=对象的当前位置+手指的当前位置-手指的初始位置

这是我到目前为止得到的

        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            if (touch.phase == TouchPhase.Began)
            {
                Vector3 startPos = touch.position;  //Initial Position
            }
            if (touch.phase == TouchPhase.Moved)
            {
                Vector3 movementDistance = new Vector3(touch.position.x - startPos.x, 0, 0);
                Vector3 direction = Camera.main.ScreenToWorldPoint(movementDistance);
                Vector3 currentPos = Camera.main.ScreenToWorldPoint(transform.position);
                transform.position = new Vector3(Mathf.Clamp(currentPos.x + direction.x, -121, 121), transform.position.y, transform.position.z);
            }
        }
由于某些原因,这不能正常工作。物体传送到随机位置,但它并没有像我希望的那样移动物体

你能帮我发现我的问题吗?如果没有,您知道其他方法吗?

请阅读“变量范围”——

试试这个:

Vector3 startPos;
float movementSpeed = 0.1f; // adjust this to your liking

void Update()
{
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
        if (touch.phase == TouchPhase.Began)
        {
            startPos = touch.position;  //Initial Position
        }
        if (touch.phase == TouchPhase.Moved)
        {
            Vector3 movementDistance = new Vector3(touch.position.x - startPos.x, 0, 0);
            Vector3 direction = Camera.main.ScreenToWorldPoint(movementDistance);
            transform.position = new Vector3(Mathf.Clamp(transform.position.x + movementSpeed * direction.x, -121, 121), transform.position.y, transform.position.z);
        }
    }
}

最后我发现了错误。他们如下:1)你说的2)我用了错误的逻辑。对象的当前位置=对象的当前位置+手指的当前位置-手指的初始位置,但我应该使用对象的当前位置=对象的初始位置+手指的当前位置-手指的初始位置。无论如何,谢谢你抽出时间