简体   繁体   English

避免自我冲突

[英]Avoiding Collisions With Self in Unity

I'm firing lasers from a cannon in a 2d space game in unity using the following method: 我使用以下方法统一在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);
}

The important bit being the Physics2D.IgnoreCollision() sections that are designed to stop them shooting themselves. 重要的是Physics2D.IgnoreCollision()部分,旨在阻止它们自行拍摄。 This works exactly as expected on the host (you can shoot the other ships but not yourself) but the lasers constantly hit their own ship on the client machines. 这完全可以在主机上按预期工作(您可以射击其他舰只,但不能射击自己),但是激光会不断在客户端计算机上击中他们自己的舰只。

As you can see here: 如您所见:

演示

This is my first attempt at making a multiplayer game in Unity so any help would be appreciated. 这是我在Unity中制作多人游戏的第一次尝试,因此将不胜感激。

Alternatively, you could add a tag to your player, like "Player" and check in OnCollisionEnter2D whether or not the bullet is colliding with the player that way: 另外,您可以在播放器中添加一个标签,例如“ 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);
}

Another way is to give the player a different layer to the bullets and ignore collisions between the player and bullet layers: 另一种方法是为播放器提供不同的子弹层,而忽略播放器和子弹层之间的碰撞:

Physics2D.IgnoreLayerCollision(PlayerLayer, BulletLayer, true);

Or go to Edit > Project Settings > Physics 2D and choose which layers collide with each other there: 或转到“编辑”>“项目设置”>“ Physics 2D”,然后选择其中哪些层相互碰撞: 碰撞矩阵

You would probably want to add your own custom layers for Player and Bullets. 您可能需要为播放器和项目符号添加自己的自定义图层。

在激光的OnCollisionEnter2D中,通过比较ID检查gameObject是否为“自己”

If( collider.gameObject.GetInstanceID() != yourself.gameObject.GetInstanceID() )

go to Edit > Project Settings > Physics 2D and choose which layers collide with each other there: 转到“编辑”>“项目设置”>“ Physics 2D”,然后选择其中哪些层相互碰撞:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM