首页 > 解决方案 > Collider2d.bounds.Intersects 未检测到交叉点

问题描述

我正在制作一个自上而下的游戏,您可以在其中驾驶汽车并同时射击目标。我有一个脚本,可以使十字准线的精灵跟随鼠标光标,我想对其进行设置,以便当玩家按下鼠标按钮(鼠标按钮现在不在代码中)并且十字准线精灵重叠时一个敌人的精灵,敌人死了。我在 Bounds.Intersects 上关注这个文档。这是我的代码:

public class shootingScript : MonoBehaviour
{

    public GameObject target, enemy;
    CircleCollider2D targetCollider;
    CapsuleCollider2D enemyCollider;

    // Start is called before the first frame update
    void Start()
    {
        //Check that the first GameObject exists in the Inspector and fetch the Collider
        if (target != null)
        {
            print("targ not null");
            targetCollider = target.GetComponent<CircleCollider2D>();
        }
        //Check that the second GameObject exists in the Inspector and fetch the Collider
        if (enemy != null)
        {
            print("enemy not null");
            enemyCollider = enemy.GetComponent<CapsuleCollider2D>();
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (targetCollider.bounds.Intersects(enemyCollider.bounds))
        {
            print("hit");
            Destroy(enemy);
        }
    }
}

游戏中会打印“targ not null”和“enemy not null”,但是当我移动光标并且十字准线越过敌人时,不会打印“hit”并且敌人不会被摧毁。我在十字准线上有一个 CircleCollider2D,在敌人上有一个 CapsuleCollider2D。该脚本位于一个空的游戏对象上。我也试过 sprite.bounds 但这导致我一运行游戏就杀死了敌人。

编辑:这是将十字准线精灵保持在光标上的代码。我从某个地方复制了它。我将 moveSpeed 设置为 99999,因为我希望十字准线精灵正好位于鼠标所在的位置。

public class mouseReticle : MonoBehaviour
{

private Vector3 mousePosition;
public float moveSpeed = 0.1f;

// Use this for initialization
void Start()
{

}

// Update is called once per frame
void Update()
{
    mousePosition = Input.mousePosition;
    mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
    transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
}
}

标签: c#unity3dgame-physics

解决方案


目标精灵和敌人精灵在不同的深度 (z)。


推荐阅读