请教如何在环形区域随机生成坐标点?

请教如何在下图的黑色区域随机生成坐标点?我的头大了,请大佬指点

RandomPointInCircle(r1:number, r2: number): cc.Vec2 {
    let PI = 3.1415926
    let CurrentR = r1 + (Math.random() * (r2 - r1))
    let CurrentAngle = Math.random() * 360;
    let targetPos = cc.v2()
    targetPos.x = Math.sin(CurrentAngle * PI / 180) * CurrentR
    targetPos.y = Math.cos(CurrentAngle * PI / 180) * CurrentR
    return targetPos
}

你这个随机取点的位置分布不均匀

醍醐灌顶!膜拜大佬!

那有啥改进方法吗?

思路明白了,就是这里还看不懂,隐隐感觉是我的数学没学好。。用了什么公式吗?Math.sin(CurrentAngle * PI / 180)

得补习一下角度弧度互相转换

// 假设内圈半径

    let inradius = 10;

    // 外圈半径let

    let outradius = 20;

    // 随机x坐标

    let x = (Math.random() *  (outradius - inradius) + inradius) * (Math.random() >= 0.5 ? -1: 1);

    // 随机y坐标

    let y = (Math.random() *  (outradius - inradius) + inradius) * (Math.random() >= 0.5 ? -1: 1);

    // 随机点

    let randomP = cc.v2(x,y);
1赞

懂了,补回来了,这下全看懂了 :pray:

这样正负两两互凑,只有四个区域,看上面的解决方案可以的

好像是,哈哈,正方形的环

// 假设内圈半径

    let inradius = 10;

    // 外圈半径

    let outradius = 20;

    let x = Math.random(),y = Math.random();

    let randomP = cc.v2(x,y).normalizeSelf().mulSelf(Math.random()*(outradius - inradius) + inradius);

这样应该也可以,就是不知道分布均匀不

1赞

let x = Math.random() - 0.5, y = Math.random() - 0.5;改成这样,随机生成一万个红点image

1赞

随机取点的位置分布不均匀,内侧的点更密

把取半径的方法改一下
let currentR = Math.sqrt(r1 * r1 + Math.random() * (r2 * r2 - r1 * r1));
位置分布就会相对正常了

randomPointInCircle(r1: number, r2: number): cc.Vec2 {
let currentR = Math.sqrt(r1 * r1 + Math.random() * (r2 * r2 - r1 * r1));
let currentAngle = Math.random() * 2 * Math.PI;
let targetPos = cc.v2();
targetPos.x = Math.cos(currentAngle) * currentR;
targetPos.y = Math.sin(currentAngle) * currentR;
return targetPos;
}

3赞

Math.sqrt是啥方法?sqrt在api上都查不到 :pray:

新的知识点又增加了 :+1: