首页 > 解决方案 > 如何检查一个区域是否在统一范围内?

问题描述

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

我关注了这个 YouTube 视频:https ://www.youtube.com/watch?v=t2Cs71rDlUg 。这家伙教如何防止生成重叠。它在某种程度上对我有用,即食物的中心永远不会在障碍物内产生,但是边缘仍然会发生碰撞。我也想防止边缘碰撞。

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

我也尝试过使用:图层蒙版和所有 Physics2d 重叠功能。

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;
    }

}

该视频从未解释如何检查食物的界限。非常感谢任何形式的帮助。

标签: c#unity3d

解决方案


推荐阅读