从 javascript 中的圆中排除点
Exclude points from circle in javascript
为了在圆上获得一个随机点,我使用了这个代码:
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));
只需更改生成随机角度的方式并将其限制为一组特定角度即可。
由于我们不知道您的具体应用,因此很难说出您的实际需求。希望这对您有所帮助。
为了在圆上获得一个随机点,我使用了这个代码:
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));
只需更改生成随机角度的方式并将其限制为一组特定角度即可。
由于我们不知道您的具体应用,因此很难说出您的实际需求。希望这对您有所帮助。