簡體   English   中英

在javascript中從圓圈中排除點

[英]Exclude points from circle in javascript

為了獲得一個隨機點ona我使用這個代碼:

const position = randomCirclePoint(circleRadius, circleX, circleY);

const x = position.x;
const y = position.y;

function randomCirclePoint(circleRadius, circleX, circleY) {
    let ang = Math.random() * 2 * Math.PI,
        hyp = Math.sqrt(Math.random()) * circleRadius,
        adj = Math.cos(ang) * hyp,
        opp = Math.sin(ang) * hyp

        const x = circleX + adj;
        const y = circleY + opp;
        
    return {x, y}
}

但是我怎樣才能從循環可以取隨機點的地方排除一些點?

如果你想從圓中排除某些角度,你可以這樣做:

const randomChoice = (list) => {
    return list[Math.floor(Math.random() * list.length)];
};

const randomCirclePoint = (circleRadius, circleX, circleY) => {
    const ang = 2 * Math.PI * Math.random();
    // for example, only in the upper half
    const angUpper = Math.PI * Math.random();
    // or only in the lower half
    const angLower = Math.PI + Math.PI * Math.random();
    // or only in quadrants 1 and 3
    const angQ1Q3 = randomChoice([
        (Math.PI / 2) * Math.random(),
        Math.PI + (Math.PI / 2) * Math.random(),
    ]);
    // or only in certain small slices of the circle
    const angSpecial = randomChoice([
        (Math.PI / 4) * Math.random(),
        (Math.PI * 8) / 7 + (Math.PI / 6) * Math.random(),
        (Math.PI * 2) / 3 + (Math.PI / 6) * 4 * Math.random(),
    ]);
    const hyp = Math.sqrt(Math.random()) * circleRadius;
    const adj = Math.cos(ang) * hyp;
    const opp = Math.sin(ang) * hyp;

    const x = circleX + adj;
    const y = circleY + opp;

    return { x, y };
};

console.log(randomCirclePoint(1, 0, 0));

只需更改生成隨機角度的方式並將其限制為特定的一組角度即可。

由於我們不知道您的具體應用程序,因此很難說出您真正想要什么。 希望這會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM