c# - 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);
}
}
解决方案
目标精灵和敌人精灵在不同的深度 (z)。
推荐阅读
- php - File could not be uploaded: missing temporary directory
- php - 在 Woocommerce 3 中以编程方式创建产品时设置产品类型
- c# - construct comma separated string from "name" property of objects stored in a list
- python - Dynamically resolve a pods address for get request
- html - 仅在 Edge 中使用 @font-face 定义的自定义字体
- python - Changing 3D scatter plot color based on specific column
- ruby-on-rails - 主动模型序列化器 each_serializer 与序列化器
- berkeley-db - berkeley-db-je 的最新版本是什么?
- php - PHP mysql数据未从最后一个ID检索
- javascript - 如何为一般元素设置背景颜色,然后通过一个事件(onclick)设置特定元素(相同类型)的背景颜色?