方法一
一、获取物体的边界且在范围内任取一点
1、Create Empty,名字自取。如:testArea
2、给testArea添加Collider
3、编辑Collider大小
4、给testArea添加boundary.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class boundary : MonoBehaviour
{
public Transform testArea;
public float Xbound;
public float Ybound;
// Start is called before the first frame update
void Start()
{
if (testArea == null)
{
Debug.LogError("还没为testArea赋值");
return;
}
BoxCollider2D testAreaCollider2D = testArea.GetComponent<BoxCollider2D>();//获取testArea的碰撞体
if (testAreaCollider2D == null)
{
Debug.LogError("碰撞体不存在!");
return;
}
if (testAreaCollider2D != null)
{
Vector3 testAreaSize = testAreaCollider2D.size;//碰撞体的大小
//Debug.Log(testAreaSize);
Xbound = testAreaCollider2D.size.x / 2;
Ybound = testAreaCollider2D.size.y / 2;
Vector3 newAxis = new Vector3(Random.Range(-Xbound, Xbound), Random.Range(-Ybound, Ybound), 0); // 调取范围内的任意一点
Debug.Log(newAxis);
}
}
// Update is called once per frame
void Update()
{
}
}
5、回到Unity赋值
二、获取物体的世界坐标
Vector3 testAreaSize = testAreaCollider2D.size;//碰撞体的大小
//Debug.Log(testAreaSize);
Vector3 testAreaOffset = testAreaCollider2D.offset;//碰撞体轴心点在其父物体坐标系统的偏移量
//Debug.Log(testAreaOffset);
Vector3 testAreaMin = testArea.position - testAreaSize / 2; //碰撞体左下角的世界坐标
Vector3 testAreaMax = testArea.position + testAreaSize / 2; //右上角
方法二
一、准备工作
1、Create Empty,名字自取。如:createArea
2、重置这个物体的位置
3、添加Collider,并设置offset = 0,合适的 size
4、为createArea添加CreateArea.cs
5、回到Unity,赋值
6、测试
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateArea : MonoBehaviour
{
public Collider2D createArea;
// Start is called before the first frame update
void Start()
{
if (createArea == null)
{
Debug.LogError("找不到碰撞体!");
}
else
{
Debug.Log(createArea.bounds.min.x);
Debug.Log(createArea.bounds.max.x);
Debug.Log(createArea.bounds.min.y);
Debug.Log(createArea.bounds.max.y);
}
}
// Update is called once per frame
void Update()
{
}
}
二、获取物体的边界且在范围内任取一点
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateArea : MonoBehaviour
{
public Collider2D createArea;
// Start is called before the first frame update
void Start()
{
Vector3 newAxis = new Vector3(
Random.Range(createArea.bounds.min.x, createArea.bounds.max.x),
Random.Range(createArea.bounds.min.y, createArea.bounds.max.y),
0
);
Debug.Log(newAxis);
}
// Update is called once per frame
void Update()
{
}
}