I've been diving into learning Canvas (HTML5) on my own and I've managed to code most of a simple game engine. It's based on a 2D space theme with planets, stars, and celestial bodies. In my default "Sprite" class, there is a frame listener implemented like this:
The "baseClass" contains a function for inheriting properties and assigns "a" to "this.a". So, creating an instance like "var aTest = new Sprite({foo: 'bar'});" sets "aTest.foo = 'bar'". This is how the objects interact in my setup.
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 be independent of framerate soon.
// Gobjs is an array containing all Sprite objects in the "world".
for(i = 0; i < gobjs.length; i++){
// Check its setup, whether it wants gravity, and ensure it's not the current sprite.
if(typeof(gobjs[i].a) != undefined && !gobjs[i].a.ignoreGravity && gobjs[i].id != this.id){
// Check proximity within a certain range.
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); // Convert radian angle to degrees.
// Still figuring out the gravitational effects here.
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).
}
});
It's quite a challenge, especially that particular line which seems to make no sense at all. Degrees plus distance equals failure indeed!
this.a.angle = angletosun+(75+(distance*-1)/5);
This question leans more towards physics than Javascript, and despite reading numerous resources on orbital mathematics, it quickly goes over my head.