gpt4 book ai didi

Javascript:球体碰撞和产生的脉冲

转载 作者:行者123 更新时间:2023-12-01 00:54:33 26 4
gpt4 key购买 nike

我是一个相当新的程序员,但我正在尝试创建自己的物理引擎而不使用任何库。这是一个星际迷你高尔夫游戏。

根据行星的密度和位置,我的重力工作正常,并且我的碰撞检测工作正常,但当它们碰撞时该怎么办是我无法解决的。

行星不会移动,但使用 Javascript 进行三 Angular 函数计算结果速度被证明是非常困难的。

这是我的物理代码,使用 requestAnimationFrame 执行:

  var a = [0, 0];
// p is in the format [x, y, radius, density]
planets.forEach(function (p) {
var d = Math.sqrt((p[0] - ball.coor[0]) ** 2 + (p[1] - ball.coor[1]) ** 2);
var m = p[3] * 4 / 3 * Math.PI * p[2] ** 3;
var f = G * m / d ** 2;
var angle = Math.atan2(p[1] - ball.coor[1], p[0] - ball.coor[0]);
a[0] += f * Math.cos(angle);
a[1] += f * Math.sin(angle);
if (d < p[2] + ball.radius) {
var impulse = [0, 0];
// What to do here?
// This is the closest I got:
var velocitya = Math.atan(b.v[1] / b.v[0]);
var trianglea = Math.abs(velocitya - angle);
var currV = Math.sqrt(b.v[0] ** 2 + b.v[1] ** 2);
var newV = currV * bounciness;
var newa = (Math.PI / 2 - trianglea) * 2 + velocitya;
b.v[0] = newV * Math.cos(newa);
b.v[1] = newV * Math.sin(newa);
// Somehow I just can't get it right.
// It's the JavaScript, not the math concepts.
}
});

ball.v[0] += a[0];
ball.v[1] += a[1];
ball.coor[0] += ball.v[0];
ball.coor[1] += ball.v[1];

ball 只是高尔夫球的对象。

我尝试了各种方法,但我就是无法让碰撞正常工作。似乎处理方向和 Angular 让我感到悲伤。我做了很多研究,但我发现似乎没有任何东西可以正确解决我的问题。

这是我的问题:如何使用普通 JavaScript 计算脉冲?

注意:行星不会移动,弹跳力应该是一个变量。

最佳答案

这样的东西可以工作吗? (仔细检查语法错误)

var a = [0, 0];
// p is in the format [x, y, radius, density]
planets.forEach(function (p) {
var d = Math.sqrt((p[0] - ball.coor[0]) ** 2 + (p[1] - ball.coor[1]) ** 2);
var r = [0, 0]; //radial vector of length one from ball's center to planet's center
r[0] = (p[0] - ball.coor[0]) / d; // this is the same as cos(angle)
r[1] = (p[1] - ball.coor[1]) / d; // this is the same as sin(angle)
// I removed your implementation, it was using redundant expensive calculations
var m = p[3] * 4 / 3 * Math.PI * p[2] ** 3;
var f = G * m / d ** 2;
a[0] = a[0] + f * r[0];
a[1] = a[1] + f * r[1];
if (d < p[2] + ball.radius) {
var dot_v_r = ball.v[0] * r[0] + ball.v[1] * r[1];
ball.v[0] = bounciness * (ball.v[0] - 2 * dot_v_r * r[0]);
ball.v[1] = bounciness * (ball.v[1] - 2 * dot_v_r * r[1]);
// this is complete elastic reflection of the ball, leaving the planet stationary
// then velocity's magnitude (but not direction) is corrected with bounciness
}
});

ball.v[0] = ball.v[0] + time_step * a[0];
ball.v[1] = ball.v[1] + time_step * a[1];
ball.coor[0] = ball.coor[0] + time_step * ball.v[0];
ball.coor[1] = ball.coor[1] + time_step * ball.v[1];

//time_step is a time step, i.e. how frequently you want to update ball's position and velocity
//you can choose a value that makes the update of frames appropriate.

关于Javascript:球体碰撞和产生的脉冲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56695332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com