Есть ли способ заставить 2D-коллайдер игнорировать другой 2D-коллайдер? - PullRequest
0 голосов
/ 30 апреля 2020

В настоящее время я выполняю университетское задание, в котором мне нужно создать 2D-игру. Я выбрал go для "Подвязки Исаи c" в стиле гусеницы подземелий. Эта проблема началась с добавления коробочных коллайдеров в спрайты моей комнаты. Поколение подземелий создается точками появления на каждом игровом объекте. Есть закрытая комната, которая появляется, когда две точки появления сталкиваются и разрушаются до появления комнаты.

С добавлением коллайдеров в комнаты точки появления сталкиваются с комнатами и уничтожают их. Это происходит именно с входной комнатой из-за находящегося там разрушителя, так как комната возрождения часто имеет 4 точки возрождения, генерируемые друг над другом, поэтому эсминец удаляет их.

Ниже приведено мое поколение подземелья классы.

Мастер создания комнат:

using System.Collections.Generic;
using UnityEngine;

public class RoomSpawner : MonoBehaviour
{
    public int openingDirection;
    //1 = need bottom door
    //2 = need top door
    //3 = need left door
    //4 = need right door
    //So for a room with a door on the right, you will type 3, as a left door is needed in the next room to connect the two rooms. 

    private RoomTemplates templates;
    private int rand;
    private bool spawned = false;
    private Vector3 entryPos;

    void Start()
    {

        templates = GameObject.FindGameObjectWithTag("Rooms").GetComponent<RoomTemplates>();
        Invoke("Spawn", 0.1f);
    }

    void Spawn()
    {
        if (spawned == false)
        {
            rand = Random.Range(0, templates.bottomRooms.Length);
            if (openingDirection == 1)
            {
                //Need to spawn room with BOTTOM door
                Instantiate(templates.bottomRooms[rand], transform.position, templates.bottomRooms[rand].transform.rotation);
            }
            else if (openingDirection == 2)
            {
                //Need to spawn room with TOP door
                Instantiate(templates.topRooms[rand], transform.position, templates.topRooms[rand].transform.rotation);
            }
            else if (openingDirection == 3)
            {
                //Need to spawn room with LEFT door
                Instantiate(templates.leftRooms[rand], transform.position, templates.leftRooms[rand].transform.rotation);
            }
            else if (openingDirection == 4)
            {
                //Need to spawn room with RIGHT door
                Instantiate(templates.rightRooms[rand], transform.position, templates.rightRooms[rand].transform.rotation);
            }
            spawned = true;
        }

    }

    void OnTriggerEnter2D(Collider2D other)
    {
        entryPos = templates.entryRoom.transform.position;
        if (other.CompareTag("Spawn Point"))
        {
            if (other.GetComponent<RoomSpawner>().spawned == false && spawned == false && transform.position != entryPos)
            {
                Instantiate(templates.closedRoom, transform.position, Quaternion.identity);


            }
            spawned = true;
        }
    }
}

Шаблоны комнат:

using System.Collections.Generic;
using UnityEngine;

public class RoomTemplates : MonoBehaviour
{
    public GameObject[] bottomRooms;
    public GameObject[] topRooms;
    public GameObject[] leftRooms;
    public GameObject[] rightRooms;

    public GameObject entryRoom;
    public GameObject closedRoom;

    public List<GameObject> rooms;

    public float waitTime;
    private bool spawnedBoss;
    public GameObject boss;

    private void Update()
    {
        if(waitTime <= 0 && spawnedBoss ==false) //if the wait time is 0 and boss isnt spawned a boss will spawn.
        {
            for (int i = 0; i < rooms.Count; i++)// will run as long as i is less than the no. of elements in list
            {
                if (i == rooms.Count - 1)//lists start with an index of zero
                {
                    Instantiate(boss, rooms[i].transform.position, Quaternion.identity);//spawn boss at the room of index i's position
                    spawnedBoss = true; //stop bosses infinitly spawning
                }
            }
        } else
        {
            waitTime -= Time.deltaTime; //slowly decrease wait time value
            //we must wait before spawning boss to ensure all rooms have been spawned.
        }

    }
}

Добавление комнаты:

using System.Collections.Generic;
using UnityEngine;

public class AddRoom : MonoBehaviour
{
    private RoomTemplates templates;
    void Start()
    {
        templates = GameObject.FindGameObjectWithTag("Rooms").GetComponent<RoomTemplates>();
        templates.rooms.Add(this.gameObject);
    }
}


Разрушитель:

using System.Collections.Generic;
using UnityEngine;

public class Destroyer : MonoBehaviour
{
    private RoomTemplates templates;
    void OnTriggerEnter2D(Collider2D other)
    {
        if(gameObject.tag == "Spawn Point")
        {
            Destroy(other.gameObject);
        } else if(gameObject.tag != "Spawn Point")
        {
            Physics2D.IgnoreCollision(templates.entryRoom.GetComponent<Collider2D>(), GetComponent<Collider2D>());
        }


    }
}

1 Ответ

2 голосов
/ 30 апреля 2020

LayerMask может быть тот, который вы ищете. Вы можете сохранить игровые объекты, которые вы не хотите сталкивать, в разных слоях и изменить матрицу столкновений (ProjectSettings> Physics2D> Layer Collision Matrix), чтобы эти объекты не сталкивались друг с другом.

...