c# - 如何检查一个区域是否在统一范围内?
问题描述
我正在尝试制作一个类似于“蛇”的游戏,玩家吃掉食物,然后食物随机生成在不同的位置。复杂之处在于场景中有一些方形障碍物,玩家必须在不与障碍物碰撞的情况下通过这些障碍物来吃食物。我面临的唯一问题是食物有时会在障碍物上产生,我想解决这个问题。
我关注了这个 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;
}
}
该视频从未解释如何检查食物的界限。非常感谢任何形式的帮助。
解决方案
推荐阅读
- php - 如何修复“重定向你太多次”。
- c - 默认安装的 Code::Blocks 在程序结束时不会因“按任意键继续”而暂停
- c - “UA_ReadRequest_deleteMembers”错误问题的 OPC-UA 函数
- python - 从python检测macos中的暗模式
- xamarin - Cocossharp 精灵掩蔽
- python - 如何在嵌套字典中查找重复项或重复项?
- php - 在 RESTful API 中重写 URL
- java - Runtime.exec 不会运行 javac,但命令行会
- r - 在 r 中创建一个稀疏矩阵,每行具有一组整数值
- javascript - 未运行 Jest+Enzyme API 模拟调用测试