根据统一沿 x 轴滑动移动游戏对象
Move gameobject according to swipe along x axis in unity
我正在尝试沿 x 轴和滑动方向统一移动对象,同时保持在屏幕内部。它应该随着用户滑动的距离而移动(很像 Ketchapp 的 rush hero)。
这是我到目前为止的更新代码:
if (Input.touchCount > 0)
{
if (Input.GetTouch (0).phase == TouchPhase.Began) // Get initial Position
{
playerPos = transform.position;
//playerPos = Camera.main.ScreenToWorldPoint (playerPos);
touchPos = Input.GetTouch (0).position;
touchPos = Camera.main.ScreenToWorldPoint (touchPos);
distance = 0f;
}
else if (Input.GetTouch (0).phase == TouchPhase.Moved)
{
Vector3 pos = Input.GetTouch (0).position;
pos = Camera.main.ScreenToWorldPoint (pos);
distance = pos.x - touchPos.x;
transform.position = new Vector3 (transform.position.x + distance, transform.position.y, transform.position.z);
}
}
这个不行,我是unity菜鸟。任何帮助将不胜感激。
这里的问题是 TouchPhase.Moved
发生不止一次(手势期间的每一帧,直到它结束)。但是您的代码假定它只被调用一次。
这里有两个选择。
- 选项 1:重置起点
添加 touchPos = Input.GetTouch (0).position;
作为 TouchPhase.Moved
块的最后一行。这将有效地指示 "this distance was already handled, next frame treat the move as a new move and this is where to start from."
- 选项 2:使用绝对偏移量
将 TouchPhase.Moved
块的最后一行更改为 transform.position = new Vector3 (distance, transform.position.y, transform.position.z);
。这会将每一帧视为每个移动都被视为与原始起点的偏移量,并相应地设置 X 值。但是,这假定对象从 0 开始,并且始终沿 X 轴从 0 开始。
根据您的用例,您可能更喜欢一种方法。
我正在尝试沿 x 轴和滑动方向统一移动对象,同时保持在屏幕内部。它应该随着用户滑动的距离而移动(很像 Ketchapp 的 rush hero)。
这是我到目前为止的更新代码:
if (Input.touchCount > 0)
{
if (Input.GetTouch (0).phase == TouchPhase.Began) // Get initial Position
{
playerPos = transform.position;
//playerPos = Camera.main.ScreenToWorldPoint (playerPos);
touchPos = Input.GetTouch (0).position;
touchPos = Camera.main.ScreenToWorldPoint (touchPos);
distance = 0f;
}
else if (Input.GetTouch (0).phase == TouchPhase.Moved)
{
Vector3 pos = Input.GetTouch (0).position;
pos = Camera.main.ScreenToWorldPoint (pos);
distance = pos.x - touchPos.x;
transform.position = new Vector3 (transform.position.x + distance, transform.position.y, transform.position.z);
}
}
这个不行,我是unity菜鸟。任何帮助将不胜感激。
这里的问题是 TouchPhase.Moved
发生不止一次(手势期间的每一帧,直到它结束)。但是您的代码假定它只被调用一次。
这里有两个选择。
- 选项 1:重置起点
添加 touchPos = Input.GetTouch (0).position;
作为 TouchPhase.Moved
块的最后一行。这将有效地指示 "this distance was already handled, next frame treat the move as a new move and this is where to start from."
- 选项 2:使用绝对偏移量
将 TouchPhase.Moved
块的最后一行更改为 transform.position = new Vector3 (distance, transform.position.y, transform.position.z);
。这会将每一帧视为每个移动都被视为与原始起点的偏移量,并相应地设置 X 值。但是,这假定对象从 0 开始,并且始终沿 X 轴从 0 开始。
根据您的用例,您可能更喜欢一种方法。