Say I have a simple system, that has a large array of pixels with their own weight, velocity, coordinates etc. (by using classes) if each of those pixels can be connected to 4 other pixels (top, bottom, left, right) how could I let that object rotate, according to physics. An example of this is where I might have an array of pixels that makes a circle, and a slope, if I put the circle at the top of the slope, how would I compute the circle rotating while going down the slope?
One way you could do it is by simulating it as a grid of particles and springs, and then performing physics on each of the particles.
- For each filled pixel, if it has a filled neighbor pixel, add a spring with a rest length of 1 pixel, and a fairly high spring constant.
- Each filled pixel has a velocity, position, and mass.
At each timestemp, move all of the pixels based on their velocities.
foreach pixel p_1: p_1.position += p_1.velocity * dt;
For each pixel, check its neighbors and apply a spring force to its velocity:
foreach pixel p_2 in p_1.neighbors: // Compute vector from p1 to p2 vector2 diff = (p_2.position - p_1.position); // This is the length of the spring float length = diff.length(); // Compute the spring force between the two particles diff.normalize(); diff *= (length - 1) * springConstant * dt; // Add a force to the particle based on the spring p_1.velocity += diff / p_1.mass;
Also calculate gravity and collisions for each pixel:
foreach pixel p_1: p_1.velocity += gravity * dt; p_1.velocity += p_1.get_collision_forces() / p_1.mass * dt;
From this numerical simulation, you will get some reasonable (but pretty buggy) physics. You will also get some nice squishiness to the simulation, which could be desirable. Depending on the size of the sprite, the spring-mass model might become infeasible. At that point, you will probably want to just represent your objects as polygons rather than pixels, by creating a convex decomposition of the sprite as polygons, and throwing it into a physics simulator such as box2d.
EDIT: I should also say that if what you're looking for is rigid physics, you can still use the spring model. Just compute the geometric moments of the particles, and use these as the rigid position/orientation of your object. Be warned: very computationally expensive!