javascript - 如何在没有球反弹的情况下模拟球与球的碰撞?
问题描述
我正在尝试制作一个简单的球物理模拟器,其中球与彼此和墙壁发生碰撞。前者是我正在努力解决的问题。我希望球相互碰撞但不反弹,我只想让它们不会进入彼此内部。
代码的更多相关位:
class Particle {
constructor(x, y) {
this.pos = createVector(x, y);
this.vel = p5.Vector.random2D();
this.vel.setMag(4)
this.r = 20
}
collide() {
for (let p of particles) {
if (p5.Vector.dist(this.pos, p.pos) < this.r + p.r && this != p) {
//Collide
}
}
}
}
JSFIDDLE:https ://jsfiddle.net/7oh3p4ku/1/
解决方案
就像威廉米勒所说,你希望他们做什么而不是反弹?您可以简单地将它们分开半径 + 另一个半径。
https://jsfiddle.net/EthanHermsey/n906fdmh/21/
collide() {
for (let p of particles) {
if (this != p && p5.Vector.dist(this.pos, p.pos) < this.r + p.r) {
//a vector pointing from the other point to this point
let directionVector = p5.Vector.sub( this.pos, p.pos );
//set the magnitude of the vector to the length of both radiusses
directionVector.setMag( this.r + p.r );
//now set this.pos at a fixed distance from p.pos. In the same direction as it was before.
this.pos = p.pos.copy();
this.pos.add( directionVector );
}
}
}
此外,我将“this != p”移到了前面,这有点快,因为不必先进行距离计算。
无论如何,由于平方根计算,该距离函数非常慢,您可以尝试使用 magSq() 函数,如下所示;
collide() {
for (let p of particles) {
if ( p == this ) continue; //go to the next particle
//a vector pointing from the other point to this point
let directionVector = p5.Vector.sub( this.pos, p.pos );
//pow( this.r + p.r, 2 ) is the same as ( this.r + p.r ) * ( this.r + p.r )
if ( this != p && directionVector.magSq() < pow( this.r + p.r, 2 ) ) {
//set the magnitude of the vector to the length of both radiusses
directionVector.setMag( this.r + p.r );
//now set this.pos at a fixed distance from p.pos. In the same direction as it was before.
this.pos = p.pos.copy();
this.pos.add( directionVector );
}
}
}
推荐阅读
- android - Cmd/React Native 无法检测到我的 JAVA_HOME 环境变量
- php - 在我的插件中,为什么 $_SESSION 仅在我登录 wp-admin 时才起作用?
- yii2 - YII2 富文本编辑器
- c# - 数据集 XML 读取无法在 C# 中启用约束
- spring-boot - 无法从 KeyCloak 获取访问令牌
- javascript - 如何改进加载动画类型?
- java - 如何从 Vue 中的 Javascript 调用 Android 中的 java 函数?
- android - ARCORE 与 Android Studio(ArSceneView 库)
- latex - 乳胶中的格式化表
- jquery - 我在一个组件中有 2 个 div,在第一个 div 中我有导航 ul 列表,第二个 div 用于内容