151 字
1 分钟
cocos creator 获取不规则图形中的随机一个点
节点中添加Sprite,PolygonCollider
export function getRandomPointInPolygon(quyu: cc.Node): cc.Vec2 {
const points = quyu.getComponent(cc.PolygonCollider).points;
let minX = Number.MAX_VALUE;
let minY = Number.MAX_VALUE;
let maxX = Number.MIN_VALUE;
let maxY = Number.MIN_VALUE;
// 获取不规则形状区域的边界框
for (let i = 0; i < points.length; i++) {
const point = points[i];
minX = Math.min(minX, point.x);
minY = Math.min(minY, point.y);
maxX = Math.max(maxX, point.x);
maxY = Math.max(maxY, point.y);
}
let randomX: number, randomY: number;
let isInsidePolygon = false;
// 在边界框内生成随机点,并检查是否在不规则形状区域内
while (!isInsidePolygon) {
randomX = randomInt(minX, maxX);
randomY = randomInt(minY, maxY);
isInsidePolygon = cc.Intersection.pointInPolygon(
cc.v2(randomX, randomY),
points
);
}
return cc.v2(randomX, randomY);
}
function randomInt(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}