使对象移动到鼠标点击位置2d

本文关键字:位置 2d 鼠标 对象 移动 | 更新日期: 2023-09-27 18:15:51

这是unity中3D的代码。我把它改成了2D的形式,但是这个物体在2D的世界里是不会移动的。作者说如果我把这个词从3D改成2D就可以了,但是我好像漏掉了什么。

private bool flag = false;
private Vector2 endPoint;
public float duration = 50.0f;
private float yAxis;
void Start()
{
    yAxis = gameObject.transform.position.y;
}
void Update()
{
    if ((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) || (Input.GetMouseButtonDown(0)))
    {
        RaycastHit hit;
        Ray ray;
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            flag = true;
            endPoint = hit.point;
            endPoint.y = yAxis;
            Debug.Log(endPoint);
        }
    }
    if (flag && !Mathf.Approximately(gameObject.transform.position.magnitude, endPoint.magnitude))
    {
        gameObject.transform.position = Vector2.Lerp(gameObject.transform.position, endPoint, 1 / (duration * (Vector2.Distance(gameObject.transform.position, endPoint))));
    }
    else if (flag && Mathf.Approximately(gameObject.transform.position.magnitude, endPoint.magnitude))
    {
        flag = false;
        Debug.Log("I am here");
    }
}

使对象移动到鼠标点击位置2d

假设这段代码工作正常,你想做的就是让它在2D中工作

RaycastHit应为RaycastHit2D

Ray应为Ray2D

Physics.Raycast应该是Physics.Raycast2D

你所要做的就是将2D添加到这些API的末尾,然后在编辑器中将所有碰撞器更改为colliders 2D。例如,Box Collider应该替换为Box Collider 2D

替换:

RaycastHit hit;
Ray ray;
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
    flag = true;
    endPoint = hit.point;
    endPoint.y = yAxis;
    Debug.Log(endPoint);
}

Vector2 ray = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray, Vector2.zero);
if (hit)
{
    flag = true;
    endPoint = hit.point;
    endPoint.y = yAxis;
    Debug.Log(endPoint);
}

这里有两件事可能是错误的:

1)你可能不会得到Raycast点击

Raycast在场景中需要3D Colliders。如果你没有它们,你就无法获得命中,因此代码的移动部分永远不会被激活。

2)你可能会混合2D和3D

如果你是在一个纯2D设置,你将不得不使用Physics2D而不是Physics。所以它将是Physics2D.Raycast。
这也需要你使用2D Colliders。一个例子是PolygonCollider2D

基本上:如果类不以2D结束,它将无法与物理2D。