gpt4 book ai didi

二维空间中的 Javascript 物理

转载 作者:数据小太阳 更新时间:2023-10-29 05:31:00 26 4
gpt4 key购买 nike

因此,我正在努力自学 Canvas (HTML5) 并编写了大部分简单的游戏引擎代码。它是空间场景(行星、恒星、天体等)的二维表示。我的默认“Sprite”类有一个像这样的帧监听器:

“baseClass”包含一个允许继承并将“a”应用于“this.a”的函数。所以,“var aTest = new Sprite({foo: 'bar'});”会使“aTest.foo = 'bar'”。这就是我将对象相互公开的方式。

Sprite = baseClass.extend({
init: function(a){
baseClass.init(this, a);
this.fields = new Array(); // list of fields of gravity one is in. Not sure if this is a good idea.
this.addFL(function(tick){ // this will change to be independent of framerate soon.

// gobjs is an array of all the Sprite objects in the "world".
for(i = 0; i < gobjs.length; i++){

// Make sure its got setup correctly, make sure it -wants- gravity, and make sure it's not -this- sprite.
if(typeof(gobjs[i].a) != undefined && !gobjs[i].a.ignoreGravity && gobjs[i].id != this.id){
// Check if it's within a certain range (obviously, gravity doesn't work this way... But I plan on having a large "space" area,
// And I can't very well have all objects accounted for at all times, can I?
if(this.distanceTo(gobjs[i]) < this.a.size*10 && gobjs[i].fields.indexOf(this.id) == -1){
gobjs[i].fields.push(this.id);
}
}
}
for(i = 0; i < this.fields.length; i++){
distance = this.distanceTo(gobjs[this.fields[i]]);

angletosun = this.angleTo(gobjs[this.fields[i]])*(180/Math.PI); // .angleTo works very well, returning the angle in radians, which I convert to degrees here.

// I have no idea what should happen here, although through trial and error (and attempting to read Maths papers on gravity (eeeeek!)), this sort of mimics gravity.
// angle is its orientation, currently I assign a constant velocity to one of my objects, and leave the other static (it ignores gravity, but still emits it).
// This cant be right, because it just _sets_ the angle regardless of whatever it was.
// This is where we need to find "the average of the forces".
this.a.angle = angletosun+(75+(distance*-1)/5); //todo: omg learn math

if(this.distanceTo(gobjs[this.fields[i]]) > gobjs[this.fields[i]].a.size*10){
this.fields.splice(i); // out of range, stop effecting.
}
}
});

//draw objects based on new position (from fixed velocity and angle).

}
});

提前致谢。真正的诀窍是那一行,顺便说一句,我知道这毫无意义。度数 + 距离 = 失败。

this.a.angle = angletosun+(75+(distance*-1)/5);

这比 Javascript 更像是一个物理问题,但我搜索并阅读了很多关于轨道数学的维基文章方式很快我就忘记了。

最佳答案

哦,这让我想起了往事,玩物理模拟非常有趣。

无论如何,听起来你需要完善你的矢量数学,这可能是最重要的事情,这篇文章应该包含你需要知道的关于矢量数学的一切,虽然我不确定它是否是最简单的可用资源。 http://en.wikipedia.org/wiki/Euclidean_vector

您的代码似乎有点过度面向对象,当然这是一个偏好问题,但我会坚持使用纯数据对象并将逻辑保留在单独的函数中。

这里有一些物理数学可以帮助您入门,每个对象都应该有一个矢量位置、一个矢量速度和质量。

对于每个刻度你做两件事,对于每个对象你将速度添加到位置:

p=p+v

对于每个物体相对于其他每个物体,您根据计算出的引力改变速度。由于 A 的引力井,B 的速度会像这样变化:

B.v=B.v+(A.p-B.p)*(A.m/(|A.p-B.p|^3))

一旦你破解了矢量数学,你应该能够将其转化为实际代码。

关于二维空间中的 Javascript 物理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2748090/

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