graphics - 球对球碰撞解决方案
问题描述
我在 youtube 上浏览了一些碰撞检测教程,在其中一个教程中,这个家伙使用以下代码来解决两个球之间的碰撞:
/**
* Rotates coordinate system for velocities
*
* Takes velocities and alters them as if the coordinate system they're on was rotated
*
* @param Object | velocity | The velocity of an individual particle
* @param Float | angle | The angle of collision between two objects in radians
* @return Object | The altered x and y velocities after the coordinate system has been rotated
*/
function rotate(velocity, angle) {
const rotatedVelocities = {
x: velocity.x * Math.cos(angle) - velocity.y * Math.sin(angle),
y: velocity.x * Math.sin(angle) + velocity.y * Math.cos(angle)
};
return rotatedVelocities;
}
/**
* Swaps out two colliding particles' x and y velocities after running through
* an elastic collision reaction equation
*
* @param Object | particle | A particle object with x and y coordinates, plus velocity
* @param Object | otherParticle | A particle object with x and y coordinates, plus velocity
* @return Null | Does not return a value
*/
function resolveCollision(particle, otherParticle) {
const xVelocityDiff = particle.velocity.x - otherParticle.velocity.x;
const yVelocityDiff = particle.velocity.y - otherParticle.velocity.y;
const xDist = otherParticle.x - particle.x;
const yDist = otherParticle.y - particle.y;
// Prevent accidental overlap of particles
if (xVelocityDiff * xDist + yVelocityDiff * yDist >= 0) {
// Grab angle between the two colliding particles
const angle = -Math.atan2(otherParticle.y - particle.y, otherParticle.x - particle.x);
// Store mass in var for better readability in collision equation
const m1 = particle.mass;
const m2 = otherParticle.mass;
// Velocity before equation
const u1 = rotate(particle.velocity, angle);
const u2 = rotate(otherParticle.velocity, angle);
// Velocity after 1d collision equation
const v1 = { x: u1.x * (m1 - m2) / (m1 + m2) + u2.x * 2 * m2 / (m1 + m2), y: u1.y };
const v2 = { x: u2.x * (m1 - m2) / (m1 + m2) + u1.x * 2 * m2 / (m1 + m2), y: u2.y };
// Final velocity after rotating axis back to original location
const vFinal1 = rotate(v1, -angle);
const vFinal2 = rotate(v2, -angle);
// Swap particle velocities for realistic bounce effect
particle.velocity.x = vFinal1.x;
particle.velocity.y = vFinal1.y;
otherParticle.velocity.x = vFinal2.x;
otherParticle.velocity.y = vFinal2.y;
}
}
我基本上理解了这段代码。但是,我无法理解如果条件如何确定球是否重叠。
if (xVelocityDiff * xDist + yVelocityDiff * yDist >= 0)
有人可以解释一下吗?
解决方案
推荐阅读
- regex - 如何使用 RegEx 删除 Mat-Input 中的空白和特殊字符
- javascript - 使用 asnyc 管道检索数据的 HTML 中的 Angular 6 问题
- java - 参数索引超出范围(1 > 参数个数,即 0)。如何解决?
- python - “ValueError:没有足够的值来解包(预期 3,得到 1)”来自 str.split() 的错误
- python - numpy数组中元素的访问属性
- linux - Linux, ignore reference to a $variable on command line. Take literal string instead
- excel - Copying table from Excel to Word bookmark using VBA
- c - How to long value compare?
- python - Requesting intraday historical data via Bloomberg API in python
- mysql - MySQL 选择 - 首先获取指定的列,然后是所有其他列(星号) - 错误 1064