我使用以下方法统一在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);
或转到“编辑”>“项目设置”>“ Physics 2D”,然后选择其中哪些层相互碰撞:
您可能需要为播放器和项目符号添加自己的自定义图层。