# PhysJ: Physics Engine Javascript

PhysJ project blog

# Making Physics Engine - Vector Implementation

February 3, 2010 03:27 by Stefano Simula
Mathematically a vector is an element of a vector space: a strcuture that displays certain mathematical properties for addition and multiplication. For my pupposes the only vector spaces i am interested in are reagular 2D spaces.
Vector are usually represented as an ordered list of numbers that can be treated in a similar way to single number in an algebraic equation. Vectors can undergo the same mathematical operations as scalar, including multiplication,addition, and subtraction.

Javascript have not a vector data structure, so this is my implementation of mathematical vector:

function vector() {

`    this.x = 0;    this.getCoordX = function() { return this.x; }        this.y = 0;    this.getCoordY = function() { return this.y; }        this.z = 0;    this.getCoordZ = function() { return this.z; }        // Sets given coords    this.setCoords = function(x, y, z) {        this.x = x;        this.y = y;        this.z = z;    }    // Flips all the components of the vector    this.invert = function() {        this.x = - this.x;        this.y = - this.y;        this.z = - this.z;    }        // Adds two vectors    this.add = function(v) {        var v = vector()        v.setCoords(this.x + v.getCoordX,                    this.y + v.getCoordY,                    this.z + v.getCoordZ);        return v;        }        // Subtracts the second vector from the first    this.subtract = function(vector) {        var v = vector()        v.setCoords(this.x - v.getCoordX,                    this.y - v.getCoordY,                    this.z - v.getCoordZ);        return v;    }         this.scalarProduct = function(k) {        this.x *= k;        this.y *= k;        this.z *= k;    }}`

Note. Many programming languages have a vector data structure which is some kind of growable array. I will call it with the name "vector" reserved for the mathematical concept.

# Making Physics Engine - The force gravity

February 3, 2010 01:50 by Stefano Simula
The force gravity is the most important force in a physics engine. The law of universal gravitation is:
f = G ((m1 m2) / r2)
where m1 and m2 are masses of the two objects, r is the distance between theri centers, f is the resulting force, and G is the "universale gravitational constant" - a scaling factor derived from observation of planetary motion. Because i am only interested in the pull of the earth, i can simplify equation: i can assume that m1 is always constant and that r is also constant.
f= m g
where m is the mass of the object i am simulating, f is the force. The constant g is an acceleration, which i measure in meters per second (on Earth this constant has a value of around 9.807 m/s2) .
Notice that the force depends on the mass of the object:
g = 1 / m f
In my engine, the most significant force we need to apply can be applied directly as an acceleration.

The value of g

Creating simulation with a g value of 10 m/s2 can look insipid. Most developer use higher values, from around 15 m/s2 for shooters to 10 m/s2 for driving games.
Gravity typically acts in the down direction, unless you are going for a special effect (but this is not my case).
The acceleration due to gravity can therefore be represented as a vector with the form:
g = [0 -g 0]T

# Making Physics Engine - Adding mass to object

February 3, 2010 00:04 by Stefano Simula

Now i need to store its mass so that we can correctly calculate its response to forces. Many physics engines simply add a scalar mass value for each object. There is a better way to get the same effect, however.

If the mass object is zer, then the acceleration will be infinite, as long as the force is zero. If i try to simulate a zero mass pirticle, it will cause divide-by-zero errors in the code.

It is often useful, however, to simulate infinite masses. These are object that no force of any magnitude can move. They are very useful for immovable objects in a game: the walls or floor, for example, cannot be moved during the game.

f = m a

a = 1 / m * f

I never use this form of equation, we can speed up my calcolations storing the 1 over the mass. This solve my problem for representig objects of zero or infinite mass: infinite mass objects have zero inverse mass, which is easy to set. Objects of zero mass would have an infinite inverse mass, which cannot be specified in most programming languages (include Javascript).

/** Holds mass and the inverse of mass of the object. It is more useful to hold the inverse mass
* because integration is simpler and beacuse it is more useful to have objects with infinite mass
* (immovable) tha zero mass*/
this.mass;
this.inverseMass;
this.getMass = function() { return this.mass; }
this.setMass = function(mass) {
this.mass = mass;
this.inverseMass = 1/mass;
}

# Making Physics Engine - Part III

February 2, 2010 21:30 by Stefano Simula

There are three law of the motion positied by Newton, the first two laws of motion are:

• an object continues with a constant velocity unless a force acts upon it;
• a force actiong on an object produces acceleration that is proportional to the object's mass;

The first law tell us: the velocity of the particle will never change, and its position will keep on being updated based on the velocity, but in real world this not be intuitive: moving object we see will slow and come to a stop eventually if they aren't being constantly forced along. In this case the object is experiencing a force (the force drag, or friction if it is sliding along).

In my simple physics engine i could assume that there are no forces at work. To simulate drag, i could add drag forces to the object. (this is fine for my physics engine, but it can cause problems with more complex system).

The second law gives us the mechanism by which forces alter the motion of an object. A force is something that changes the acceleration of an object. An implication of this law is that i cannot do anything to an object to directly change it position or velocity; i can only do that indirectly by applying a force to change the acceleration and wait until the object reaches our target position or velocity. Velocity and position jeep track of a quantity from frame to frame during the game. They change, but not directly, only by the influence of accelerations. Acceleration can be different from one moment to another. I can set the acceleration of an object as i see fit, and the behavior of the object will look fine. Otherwise, if i set directly the velocity or position, the object will appear to jolt or jump.

# Making Physics Engine - Part II

February 2, 2010 04:10 by Stefano Simula

Very very (very) simple physics engine: the idea is to create a simple physics engine using simple rules for the management of gravity, friction, elasticity and shock.

Physics Engine are based on Newton's laws of motion. Newton created three laws of motion that describe with grat accuracy how point mass behaves. A point mass has a position, but no orientation. For example, in a game i don't really care in what direction a bullet is pointing, i just care in what direction it is travelling and wheter it hits the target.

For each point mass, i will need to keep track of various properties:

1. position;
2. velocity;
3. acceleration;

The position, velocity and acceleration are all vectors.

The physics object can be implemented with the following:

function PhysJObject(id) {
this.id = id;

// Holds the linear position of the particle in PhysJ World
this.positionX;
this.positionY;

this.getPosition = function() { return this.position; }

this.setPosition = function(x, y) {
this.positionX = x;
this.positionY = y;
}

this.mass;

this.setMass = function() { return this.mass; }

this.setMass = function(mass) { this.mass = mass; }

// Holds the linear velocity of the object in PhysJ World
this.velocityX;
this.velocityY;

this.getVelocityX = function() { return this.velocityX; }
this.getVelocityY = function() { return this.velocityY; }

this.setVelocityX = function(velX) { this.velocityX = velX; }
this.setVelocityY = function(velY) { this.velocityY = velY; }

this.applyVelocity = function(velX, velY) {
this.velocityX += velX;
this.velocityY += velY;
}

// Holds the acceleration of the object. This value can be used to set acceleration
// due to gravity or any other constant acceleration
this.accelerationX;
this.accelerationY;

this.getAccelerationX = function() { return this.accelerationX; }
this.getAccelerationY = function() { return this.accelerationY; }

this.setAccelerationX = function(accX) { this.accelerationX = accX; }
this.setAccelerationY = function(accY) { this.accelerationY = accY; }

this.applyAcceleration = function(accX, accY) {
this.accelerationX += accX;
this.accelerationY += accY;
}

var elasticity;

this.getElesticity = function() { return this.elasticity; }

this.setElasticity = function(el) { this.elasticity = el; }

var friction;

this.getFriction = function() { return this.friction; }

this.setFriction = function(f) { this.friction = f; }

// How much energy something keeps after collision
var restitution;

this.getRestitution = function() { return this.restitution; }

this.setRestitution = function(r) { this.restitution = r; }
}

# Making Physics Engine - Part 1

January 30, 2010 02:02 by Stefano Simula

Her first major deal to develop a physics engine is to define an environment with homogeneous coordinates.

A set of objects is represented by homogeneous coordinates, where each sequence of numbers [x0, ..., xn] nothing other than the sequence, identifies an object. In addition, two sequences determine the same object if and only if they are a multiple of the other, ie if there exists a number y such that the two sequences are of the type:
[x0, ..., xn] And [y x0,. . . , y xn]
What means that the homogeneous coordinates are defined up to a factor of proportionality.

The use of homogeneous coordinates therefore has the disadvantage of not biunivocit `a representation of the points. However, an extension of the concept of homogeneous coordinates introduced above allows the study of so-called point to the infinity of the plane, the point at infinity on whose definition does not insist that restricting ourselves to the intuitive image of them you can `make or thinking variable points to `a continuity on lines and at least one component tends to + ∞ in absolute value.
A point at infinity ∞ `P` and then detected and fixed when a line. We say that P ∞ `and the point of that improper fees.
It was agreed then that parallel lines identify the same point at infinity, with which it has only two lines in the plan are always a point, possibly improper, in common.

# PhysJ

January 30, 2010 00:02 by Stefano Simula

PhysJ is a physics engine written in Javascript.

The idea is to create a development environment for creating javascript script conditioned by some simple physical laws. The question that many people do is: why

There are many javascript libraries that allow you to define the animations very "cool", but all fail till today to replace Flash that result hated by most programmers.

Many sites contain different Flash objects, from simple slideshows to complex animations. Javascript now allows you to define simple slideshow with just the use of libraries very easy to use. Unfortunately, none of these libraries in its animation is realistic to 100%. The idea of this project is to define a graphics library that allows for realistic animations, using the power of JavaScript and its speed in modern browsers. This way you will not be necessary to include Flash objects within your page, you will not need to fully discharge several kilobytes, but just a simple call to the library to have an effect simple but very evocative.