2020-10-24小记

项目场景:

贪吃蛇


问题描述(解决):

解决食物总是生成在边界或者障碍上的问题
规定生成的边界范围,获得每个障碍的长与宽,再次缩小范围,进而达到目的

 //生成不在障碍或者边界上的坐标
    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;
    }

原因分析:

范围定位不准确,只用了粗略的估值


解决方案:

上述代码即为解决方案,获得障碍的准确位置与大小范围,排除掉其范围内的坐标,可避免食物生成在障碍上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值