我在 2d 空间游戏中使用以下方法统一从大炮发射激光:
[Command]
private void CmdFire()
{
GameObject laser = (GameObject)Instantiate(LaserPrefab, leftShot ? leftCannon.position : rightCannon.position, leftShot ? leftCannon.rotation * Quaternion.Euler(0, 0, 90) : rightCannon.rotation * Quaternion.Euler(0, 0, 90));
Physics2D.IgnoreCollision(laser.GetComponent<Collider2D>(), transform.FindChild("PlayerShip").GetComponent<Collider2D>());
Physics2D.IgnoreCollision(laser.GetComponent<Collider2D>(), transform.FindChild("PlayerShip").FindChild(leftShot?"LeftCannon":"RightCannon").GetComponent<Collider2D>());
laser.GetComponent<SpriteRenderer>().sortingOrder = 0;
laser.GetComponent<Rigidbody2D>().velocity = laser.transform.right * 10;
NetworkServer.Spawn(laser);
leftShot = !leftShot;
Destroy(laser, 2f);
}
重要的一点是 Physics2D.IgnoreCollision()
部分旨在阻止它们射击自己。这在主机上完全符合预期(您可以射击其他船只但不能射击您自己)但是激光不断地击中客户端机器上自己的船只。
如你所见:
这是我第一次尝试在 Unity 中制作多人游戏,如有任何帮助,我们将不胜感激。
最佳答案
或者,您可以为您的播放器添加一个标签,例如“Player”,并在 OnCollisionEnter2D
中检查子弹是否以这种方式与播放器发生碰撞:
void OnCollisionEnter2D (Collision2D coll) {
// If the tag of the thing we collide with is "Player"...
if (coll.gameObject.tag == "Player")
Debug.Log("Player hit!");
// Ignore the collision with the player.
Physics2D.IgnoreCollision(player.collider, collider);
}
另一种方法是给玩家一个不同的子弹层,并忽略玩家和子弹层之间的碰撞:
Physics2D.IgnoreLayerCollision(PlayerLayer, BulletLayer, true);
或者转到“编辑”>“项目设置”>“2D 物理”并选择在那里相互碰撞的图层:
您可能想要为 Player 和 Bullets 添加自己的自定义层。
关于c# - 避免在 Unity 中与 self 发生冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43083636/