【问题标题】:Object target radius checking in UnityUnity中的对象目标半径检查
【发布时间】:2017-01-13 23:55:54
【问题描述】:

我正在尝试制作一个在 3 点之间移动的攻击剑。人物手中的主要位置,秋千的顶部和秋千的底部。之后它又回到手上。

我使用了通用的“地面检查跳跃”代码并对其进行了一些修改,因为在循环中使用“移向”从来没有完全命中以改变到下一阶段。

两个错误都在“reachedTarget”行;

The best overloaded method match for `UnityEngine.Physics2D.OverlapCircle(UnityEngine.Vector2, float, int)' has some invalid arguments

Argument `#3' cannot convert `UnityEngine.Vector3' expression to type `int'

这是代码。

void TargetCheck(GameObject target)
{
    //Returns true when the sword is over the target
    reachedTarget = Physics2D.OverlapCircle(transform.position, 0.1f, target.transform.position);
}

我不太确定我在这里做错了什么。感谢您的帮助:)

【问题讨论】:

  • target.transform.position 不是整数

标签: c# unity3d


【解决方案1】:

“无法将 x 表达式转换为 y 类型”总是意味着您试图在需要 y 类型的地方输入 x 类型的内容。例如: int number = "hello world";不管用。您正在尝试将 int 转换为字符串

在您的情况下,您尝试使用target.transform.position 输入int LayerMaskSee documentation on OverlapCircle

如果您不确定哪个 LayerMask 以及如何移位,请声明 public LayerMask layermask; 并让 Unity 序列化它。这将为您提供复选框按钮来填写哪些图层。

编辑:看来Vector3.Distance 是 OP 想要的!

【讨论】:

  • 啊,谢谢。所以那时我不能这样做。我还能如何查看一个对象是否足够靠近另一个对象。我有if (sword.transform.position == target.transform.position),但它从来没有完全命中,有什么办法可以为此添加半径吗?
  • 您可以拍摄 Raycast 并查看它们的长度/目标命中或添加碰撞器并检查它们何时发生碰撞!是2D游戏吧?
  • 是的,2D 游戏。我不知道如何进行 Raycast,但我会查一下并试一试。感谢您的帮助:)
  • 我试过使用光线投射,但有没有办法做到“从矢量到矢量”?我必须给它一个方向,我不知道该怎么做。我见过一些人在谈论“Linecasts”,但他们没有一个可以返回 true 的范围。 “Debug.DrawLine”函数看起来是一个 linecast 而不是 raycast。这从向量到向量,但光线投射没有。有没有什么办法可以让光线投射从一个向量到另一个向量或线路投射有一个长度来检查,而不是“它可以被看到还是之前有一个物体”
  • 向量到向量的距离?听起来像 Vector3.Distance! docs.unity3d.com/ScriptReference/Vector3.Distance.html
【解决方案2】:

您可能不需要第三个参数。那应该是您要与之碰撞的对象的图层。确保它是目标的图层 ID。

之后到达目标可能应该与目标的 Collider2D 组件进行比较。如果匹配 - 你就成功了。

为懒惰的人编辑 - 应该是这样的:

void TargetCheck(GameObject target)
{
    //Returns true when the sword is over the target
    var CollidedWith = Physics2D.OverlapCircle(transform.position, 0.1f, *LayerYouWantToCollideWith*);

    var TargetCollider2D = target.GetComponent<Collider2D>();
    bool CollidedWithTarget = CollidedWith == TargetCollider2D;
}

PS:您可能应该事先获取目标的 Collider2D 组件并将其存储在某个地方..

【讨论】:

    猜你喜欢
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2014-03-19
    相关资源
    最近更新 更多