I've been fooling around in JavaScript again, and I've come up with this simple physics simulation. I think it has a pretty simple setup, here's "psuedocode" of sorts to explain it.
- Constructor
PhysicsEntity
- Private method
_calculateForces
- Calculates forces to be applied. - Private method
_applyForces
- Apply the calculated forces. - Private method
_renderEntity
- Render thePhysicsEntity
at it's position. - Method
updateEntity
- Update the entity.
- Private method
I think the interface is pretty clear, but if you have any suggestions, they would be greatly appreciated.
/*
A simple physics object for managing
certain things such as forces acting
upon the object, and rendering.
*/
var PhysicsEntity = function(mass, entityWidth, entityHeight, accelerationVector, position, lifeTime)
{
this.mass = mass;
this.entityWidth = entityWidth;
this.entityHeight = entityHeight;
this.accelerationVector = accelerationVector;
this.position = position;
this.velocity = new PVector(0, 0);
// Calculate the forces to be applied to the velocity
this._calculateForces = function()
{
this.velocity.add(this.accelerationVector.x*this.mass, this.accelerationVector.y*this.mass);
};
// Apply velocity to the Entity's position
this._applyForces = function()
{
this.position.add(this.velocity);
};
// Render the Entity at it's position
this._renderEntity = function()
{
rect(this.position.x, this.position.y, this.entityWidth, this.entityHeight);
};
// Update the entity
this.updateEntity = function()
{
this._calculateForces();
this._applyForces();
this._renderEntity();
};
};
Here's an example of how this can be used.
// Data for creating new PhysicsEntities and storing them
var DEFAULT_MASS = 1;
var DEFAULT_WIDTH = 10;
var DEFAULT_HEIGHT = 10;
var DEFAULT_ACCELERATION = new PVector(0, 0.2);
var DEFAULT_LIFETIME = 250;
var entityArray = [];
// Create a new PhysicsEntity at the mouse
var createEntity = function()
{
entityArray.push(
new PhysicsEntity(
DEFAULT_MASS, DEFAULT_WIDTH, DEFAULT_HEIGHT,
DEFAULT_ACCELERATION, new PVector(mouseX, mouseY),
DEFAULT_LIFETIME
)
);
};
// Update all entities
var updateEntities = function()
{
for(var n = entityArray.length-1; n >= 0; n--)
{
var entity = entityArray[n];
entity.updateEntity();
}
};
// Main draw loop
draw = function() {
background(255, 0, 0);
createEntity();
updateEntities();
};