项目场景:
贪吃蛇
问题描述(解决):
解决食物总是生成在边界或者障碍上的问题
规定生成的边界范围,获得每个障碍的长与宽,再次缩小范围,进而达到目的
//生成不在障碍或者边界上的坐标
private Vector3 MakePosition()
{
int x = 0;
int y = 0;
bool isSuit = false;
while (isSuit == false)
{
isSuit = true;
x = Random.Range(-260, 500);
y = Random.Range(-262, 262);
for(int i = 0; i < barrierList.Count; i++)
{
if (barrierList[i].GetComponent<Image>().enabled)
{
int barrXMax = (int)(barrierList[i].localPosition.x + barrierList[i].GetComponent<RectTransform>().rect.width / 2.0f);
int barrXMin = (int)(barrierList[i].localPosition.x - barrierList[i].GetComponent<RectTransform>().rect.width / 2.0f);
int barrYMax = (int)(barrierList[i].localPosition.y + barrierList[i].GetComponent<RectTransform>().rect.height / 2.0f);
int barrYMin = (int)(barrierList[i].localPosition.y - barrierList[i].GetComponent<RectTransform>().rect.height / 2.0f);
if ((x <= barrXMax && x >= barrXMin) && (y <= barrYMax && y >= barrYMin)){
isSuit = false;
}
}
}
}
Vector3 pos = new Vector3(x, y, 0);
return pos;
}
原因分析:
范围定位不准确,只用了粗略的估值
解决方案:
上述代码即为解决方案,获得障碍的准确位置与大小范围,排除掉其范围内的坐标,可避免食物生成在障碍上。