unity 在Canvas下圆形范围内生成一个点

 1、创建一个圆形区域Image, 以及一个目标点Target1(Image);

2、目标点Target1的位置计算

using System;
using UnityEngine;
public class Test1 : MonoBehaviour
{
    public Transform targetImage1; //目标点
    public float _range;    //范围
    float targetObj1PoxX;
    float targetObj1PoxY;
    private void Start()
    {
        CreateThreeTargetObjPosition();
    }
    void CreateThreeTargetObjPosition()
    {
        targetObj1PoxX = UnityEngine.Random.Range(-_range, _range);
        //目标y轴坐标最大值
        float _targetObj1PoxY_Max = (float)(Math.Sqrt(_range * _range - targetObj1PoxX * targetObj1PoxX));
        //目标y轴坐标最小值
        float _targetObj1PoxY_Min = (float)(-_targetObj1PoxY_Max);
        targetObj1PoxY = UnityEngine.Random.Range(_targetObj1PoxY_Min, _targetObj1PoxY_Max);
        targetImage1.localPosition = new Vector3(targetObj1PoxX, targetObj1PoxY, 0); 
    }
}

3、在绿色区域生成一个目标点

4、目标点Target1的位置计算

using System;
using UnityEngine;
public class RandomThreeTarget : MonoBehaviour
{
    public Transform targetImage2; //目标target1
    float targetObj2PoxX;
    float targetObj2PoxY;
    float maxRange=200;
    float minRange=100;
    void Start()
    {
        CreateTargetObj();
    }
    void CreateTargetObj()
    {
        targetObj2PoxX = UnityEngine.Random.Range(-maxRange, maxRange);
        float _targetObj2PoxY_Max;
        float _targetObj2PoxY_Min;
        if (targetObj2PoxX >= minRange || targetObj2PoxX <= -minRange)
        {
            _targetObj2PoxY_Max = (int)(Math.Sqrt(maxRange * maxRange - targetObj2PoxX * targetObj2PoxX));
            _targetObj2PoxY_Min = -_targetObj2PoxY_Max;
            targetObj2PoxY = UnityEngine.Random.Range(_targetObj2PoxY_Min, _targetObj2PoxY_Max);
        }
        if (targetObj2PoxX < minRange && targetObj2PoxX > -minRange)
        {
           // Math.Sqrt  开方
           _targetObj2PoxY_Max = (int)(Math.Sqrt(maxRange * maxRange - targetObj2PoxX * targetObj2PoxX));
            _targetObj2PoxY_Min = (int)(Math.Sqrt(minRange * minRange - targetObj2PoxX * targetObj2PoxX));

            if (((int)targetObj2PoxX / 2) == 0)
            {
                targetObj2PoxY = UnityEngine.Random.Range(_targetObj2PoxY_Min, _targetObj2PoxY_Max);
            }
            else
            {
                targetObj2PoxY = -UnityEngine.Random.Range(_targetObj2PoxY_Min, _targetObj2PoxY_Max);
            }
        }
        targetImage2.localPosition = new Vector3(targetObj2PoxX, targetObj2PoxY, 0);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值