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