if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
RaycastHit2D hit;
Physics2D.Raycast(ray, out hit);
Debug.Log(hit.point);
}
public float scaleFactor = 0.2f; //how fast to move object.
public GameObject moving // drag the object you want to move in this slot.
public Vector2 Lerped;//Vector3 if you’re working in 3D.
public float time = 0f;
public bool lerping = false;
private Vector2 newPos = new Vector2();
//Vector3 if you’re working in 3D.
RaycastHit2D hit;//remove the 2D after RaycastHit if you are in 3D. If you are in 2D, leave it.
float dist;
...
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
Physics2D.Raycast(ray, out hit);//same with this one. Remove the 2D if you are in 3D.
Debug.Log(hit.point);
dist = Vector2.Distance(moving.transform.position, hit.point);
//Vector3 if you’re in 3D.
lerping = true;
}
if (lerping)
{
time += Time.deltaTime * dist * scaleFactor;
lerp(hit.point.x, hit.point.y, hit.point.z);
//remove hit.point.z if you are in 2D.
}
else
{
time = 0f;
}
if (moving.transform.position == new Vector3(hit.point.x, hit.point.y, hit.point.z);
//remove hit.point.z if in 2D, and switch Vector3 to Vector2 if in 2D.
{
lerping = false;
}
moving.transform.position = newPos;
然后在剧本的另一部分:
public void lerp(float x, float y, float z)
//remove the float z and the comma before it if you are in unity 2d.
{
Vector3 pos = new Vector3(x, y, z);
//Vector2 and no z if you’re in 2D.
newPos = Vector2.Lerp(moveObj, pos, time);
//Vector3 if in 3D.
}
1条答案
按热度按时间balp4ylt1#
您应该使用Vector2.Lerp、Input.GetTouch和Touch.Position。下面是打印当前触摸位置的代码示例:
现在,我们应该把这个加到世界上的某个位置上。我们可以使用Camera.ScreenPointToRay来处理这部分:
在这里,我们实际上得到了你所按下的世界中的位置。然后,我们可以使用这个沿着Lerp将对象移动到位置:
然后在剧本的另一部分:
这是一个相当大的脚本,很难解释,所以我会这样说:按照注解的要求做,如果有错误请告诉我。我还没有真正测试过这个脚本,所以如果有人注意到它们,请告诉我。
现在,脚本做什么:基本上,它会得到你触摸的点,并使玩家慢慢地向它移动(速度会随着距离和scaleFactor变量的变化而变化,你可以改变这个变量)。