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