问题描述
我正在制作一款自上而下的游戏,您可以在驾驶汽车的同时射击目标。我有一个脚本,使十字准线的精灵跟随鼠标光标,我想设置它,以便当玩家按下鼠标按钮(鼠标按钮现在不在代码中)并且十字准线精灵重叠时一个敌人的精灵,敌人死了。我在 Bounds.Intersects 上关注了 this documentation。这是我的代码:
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)。