use*_*123 6 javascript physics canvas
所以,我正在自学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).
}
});
Run Code Online (Sandbox Code Playgroud)
提前致谢.真正的诀窍是一条线,顺便说一下,我知道它没有任何意义.度+距离=失败.
this.a.angle = angletosun+(75+(distance*-1)/5);
Run Code Online (Sandbox Code Playgroud)
这比JavaScript中的物理问题,但我已经搜查,搜查和阅读的方式对轨道的数学许多维基文章.它得到了我的头非常快.
哦,这让我想起了,玩物理模拟真是太有趣了。
无论如何,听起来您需要完善矢量数学,这可能是最重要的问题,本文应该包含您需要了解的有关矢量数学的所有内容,尽管我不确定它是否是最简单的可用方法来源。http://en.wikipedia.org/wiki/Euclidean_vector
您的代码似乎有点过度面向对象,当然这很大程度上是一个偏好问题,但我会坚持使用纯数据对象并将逻辑保留在单独的函数中。
这里有一些物理数学知识可以帮助您入门,每个物体都应该有一个作为向量的位置、一个作为向量的速度和质量。
对于每个刻度,您做两件事,对于每个对象,您将速度添加到位置:
p=p+v
Run Code Online (Sandbox Code Playgroud)
对于每个物体相对于其他物体的速度,您可以根据计算出的引力来改变速度。由于 A 的重力井,B 的速度会发生如下变化:
B.v=B.v+(A.p-B.p)*(A.m/(|A.p-B.p|^3))
Run Code Online (Sandbox Code Playgroud)
一旦你破解了矢量数学,你应该能够将其转化为真正的代码。
| 归档时间: |
|
| 查看次数: |
871 次 |
| 最近记录: |