保持圈子不重叠 [英] Keeping circles from overlapping

查看:129
本文介绍了保持圈子不重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这张图片的左侧是一个可视化的代表什么东西,我已经有:



x1,y1,x2和y2是圆的位置,r1和r2是圆的半径, θ是相对于画布x轴的圆之间的夹角。



如何计算新的[x,y ]这两个圈子的位置,这样他们就像图片右侧显示的那样推彼此?



我也计划使小圆圈比大圆圈更大。通过使用标准化半径作为乘数,这应该很容易。

只需取中心之间的矢量差
var dx = x2 - x1;
var dy = y2 - y1;

//计算这个向量的长度
var L = Math.sqrt(dx * dx + dy * dy);

//计算您需要移动的金额
var step = r1 + r2 - L;

//如果发生碰撞,您将有步骤> 0
if(step> 0){
//在这种情况下,将矢量归一化
dx / = L; dy / = L;

//然后将这两个中心分开
x1 - = dx * step / 2; y1 - = dy * step / 2;
x2 + = dx * step / 2; y2 + = dy * step / 2;
}


I'm trying to figure out the JavaScript math to move two colliding circles apart from each other.

The left side of this image is a visual representation of what I already have:

x1, y1, x2 and y2 are the positions of the circles, r1 and r2 are the radii of the circles, theta is the angle between the circles in relation to the x-axis of the canvas.

How do I calculate the new [x,y] positions for both circles, so that they "push" each other apart as demonstrated on the right side of the image?

I'm also planning to make the smaller circle be pushed more than the larger one. That should be easy enough by using their normalized radii as a multiplier.

解决方案

// Just take the vector difference between the centers
var dx = x2 - x1;
var dy = y2 - y1;

// compute the length of this vector
var L = Math.sqrt(dx*dx + dy*dy);

// compute the amount you need to move
var step = r1 + r2 - L;

// if there is a collision you will have step > 0
if (step > 0) {
    // In this case normalize the vector
    dx /= L; dy /= L;

    // and then move the two centers apart
    x1 -= dx*step/2; y1 -= dy*step/2;
    x2 += dx*step/2; y2 += dy*step/2; 
}

这篇关于保持圈子不重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆