【问题标题】:make object move to the mouse clicked position 2d使对象移动到鼠标单击的位置 2d
【发布时间】:2016-11-02 18:49:44
【问题描述】:

这是统一 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");
    }
}

【问题讨论】:

  • flag 是否曾经设置为 true?
  • @Dawnkeeper 是的,看看里面if (Physics.Raycast(ray, out hit))
  • 我的意思是代码在调试时是否真的到达了这条指令。 =) 他可能不会受到 Raycast 的命中。
  • 嗯,好的。我虽然你的意思是他没有在代码中的任何地方将其设置为 true

标签: c# unity3d 2d


【解决方案1】:

假设这段代码工作正常,你要做的就是让它在 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);
}

【讨论】:

    【解决方案2】:

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

    1) 您可能无法获得Raycast 命中

    Raycast 需要场景中的 3D 碰撞器。如果您没有它们,您将无法获得成功,因此代码的移动部分永远不会被激活。

    2) 您可能正在混合 2D 和 3D

    如果您使用的是纯 2D 设置,则必须使用 Physics2D 而不是 Physics。所以它将是Physics2D.Raycast
    这也将要求您使用 2D 对撞机。一个例子是PolygonCollider2D

    基本上:如果类不以 2D 结尾,则它不适用于 Physics2D。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多