如何检查区域是否在特定范围内?

时间:2019-07-18 16:19:34

标签: c# unity3d

我正在尝试制作类似“蛇”的游戏,在该游戏中,玩家吃掉食物,然后在不同的位置随机产生食物。复杂之处在于场景中存在一些方形障碍物,玩家必须通过这些障碍物进行机动才能吃食物而不与障碍物碰撞。我面临的唯一问题是食物有时会在障碍物上方产生,我想解决这个问题。

我关注了以下YouTube视频:https://www.youtube.com/watch?v=t2Cs71rDlUg。 那家伙教什么方法防止产卵重叠。它在某种程度上对我有用,那就是食物的中心永远不会在障碍物内部产生,但是边缘仍然会碰撞。我也想防止边缘碰撞。

那家伙使用食物对象的中心来检查碰撞,而不是检查食物的整个区域(这是一个带有圆对撞机的圆圈)。

我还尝试使用:图层蒙版和所有Physics2d Overlap函数。

using UnityEngine;

public class foodspawner : MonoBehaviour
{
    public static FoodSpawner2 instance;
    public float xbound;
    public float ybound;
    public GameObject foodPrefab;
    public GameObject currentFood;
    public LayerMask mask;

    public Vector2 one = new Vector2(50f, 50f);
    public Vector2 two = new Vector2(-50f, -50f);

    public float radius;
    public Collider2D[] collidersss;
    //Spawns the food for the first time
    void Start()
    {
        FoodLoaction();
    }

    private void Update()
    {
        //Spawns the food when it gets eaten by the snake
        if (currentFood == null)
        {
            FoodLoaction();
        }
        FoodLoaction();
    }

    public void FoodLoaction()
    {
        Vector2 SpawnPos = new Vector2();
        bool canSpawnHere = false;
        int safetynet = 0;

        while (!canSpawnHere)
        {
            float xPos = Random.Range(-xbound, xbound);
            float yPos = Random.Range(-ybound, ybound);

            SpawnPos = new Vector2(xPos, yPos);
            canSpawnHere = PreventSpawnOverlap(SpawnPos);

            if (canSpawnHere)
            {
                break;
            }

            safetynet++;

            if (safetynet > 50)
            {
                break;
                Debug.Log("toooooooo");
            }
        }

        currentFood = Instantiate(foodPrefab, SpawnPos, Quaternion.identity) as GameObject;

    }

    public bool PreventSpawnOverlap(Vector2 spawnPos)
    {
        collidersss = Physics2D.OverlapCircleAll(transform.position, radius, mask);
        for (int i = 0; i < collidersss.Length; i++)
        {
            Vector2 centerpoint = collidersss[i].bounds.center;
            float width = collidersss[i].bounds.extents.x;
            float height = collidersss[i].bounds.extents.y;

            float leftExtent = centerpoint.x - width;
            float rightExtent = centerpoint.x + width;
            float lowerExtent = centerpoint.y - height;
            float upperExtent = centerpoint.y + height;

            if (spawnPos.x >= leftExtent && spawnPos.x <= rightExtent)
            {
                if (spawnPos.y >= lowerExtent && spawnPos.y <= upperExtent)
                {
                    return false;
                }
            }
        }
        return true;
    }

}

视频从未说明如何检查食物的界限。任何帮助都将不胜感激。

0 个答案:

没有答案