【问题标题】:Raycasting in Unity 2D c#Unity 2D c#中的光线投射
【发布时间】:2014-05-26 01:43:47
【问题描述】:

我是 c# 的新手,正在尝试弄清楚如何在 Unity3d 的新 2d 支持中让光线投射在这里工作。

我收到错误“无法从 'UnityEngine.Ray2D' 转换为 'UnityEngine.Vector2'”

for (int i = 0; i<3; i ++) {
        float dir = Mathf.Sign(deltaY);
        float x = (p.x + c.x - s.x/2) + s.x/2 * i;
        float y = p.y + c.y + s.y/2 * dir;

        ray = new Ray2D(new Vector3(x, y), new Vector3(0, dir));
        Debug.DrawRay(ray.origin, ray.direction);
        hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Abs(deltaY), collisionMask);

        if (hit != null && hit.collider != null)
        {
        }
        if (Physics2D.Raycast(ray,out hit,Mathf.Abs(deltaY),collisionMask)) {
            float dst = Vector2.Distance (ray.origin, hit.point);

            if (dst > skin) {
                deltaY = dst * dir + skin;
            }
            else {
                deltaY = 0;
            }

            grounded = true;

            break;

        }
    }

谁能帮帮我?

【问题讨论】:

  • 错误出现在哪一行?
  • if (Physics2D.Raycast(ray,out hit,Mathf.Abs(deltaY),collisionMask))

标签: c# unity3d 2d raycasting


【解决方案1】:

参见Physics2D.Raycast文档,方法定义为

static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);

参数定义为

origin:2D 空间中射线的起源点。

direction:表示光线方向的向量。

距离:投射光线的最大距离。

layerMask:过滤以仅在某些图层上检测碰撞器。

minDepth:仅包括 Z 坐标(深度)大于此值的对象。

maxDepth:仅包含 Z 坐标(深度)小于此值的对象。

对于origin,您使用的是Ray2D,而不是Vector2D。如果您只是将ray 替换为Vector2D,它将起作用

Physics2D.Raycast(new Vector2(x, y),out hit,Mathf.Abs(deltaY),collisionMask)

欲了解更多信息,请参阅passing parameters

【讨论】:

    【解决方案2】:
    1. 像之前在代码中那样调用:

      hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Abs(deltaY), collisionMask);

    2. 这段代码没用:

      if (hit != null && hit.collider != null) { }

    但是如果你需要在括号中输入一些逻辑——你不需要检查hit是否为null——它总是一个对象,只需检查hit.collider

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      相关资源
      最近更新 更多