I Tried Making a Confetti Effect with Physics Simulation
Click the screen to go to the WebGL sample. There's a video too.
Hello. I'm Hirayama from the Technology Department.
Recently I happened to have a chance to make a confetti-like effect, so I'd like to present it as "an applied example that combines the basic techniques I've written about so far".
I've put the code on GitHub. And for those who want to drop it in and give it a quick try, there's a package too.
How to use it
Import the package, place the Confetti prefab that comes in it somewhere, and something will show up. With the default settings you can't really make it out unless you look from about 100 units away, so watch the distance from the camera.
It's only a sample, so it's not very customizable. If changing parameters isn't enough, modify it or make your own. I recommend making your own. It'll put quite a range of knowledge to the test.
Knowledge needed to make it
The areas of knowledge used are roughly these.
- 3D vector math
- Point-mass physics (the kind you do in high school)
- A bit of quaternions (including integration)
- Instancing-like drawing using skinning
Related past articles include:
- Trackball-style camera control using quaternions
- Rotating vectors in 3D space
- Tracking (homing) calculation for beams and missiles
- Mass drawing like instancing using skinning
You don't have to understand these articles first, but this one is closely tied to them.
Starting from a single scrap of paper
Let's start by making the behavior of a single scrap of paper. Once that's done, all that's left is to put out lots of them. This time I'm assuming "scraps of paper don't collide with or affect each other", so the only problem when the number of scraps grows is processing speed. And even there, I've only done "what can be done right away", and saved the parts that take effort (in other words, the fun parts) for another time.
Point-mass physics
The simplest kind of physics simulation is the simulation of a point mass.
It has no size, so you don't need to think about rotation.
It has no size, so you don't even need the concept of shape.
Compared with the rigid body physics built into Unity, it's far easier to handle. Using rigid bodies for something point masses can do is a waste, so you should first think about whether point masses can do it.
Implementing the equation of motion
Put simply, point-mass physics can be written with the following code.
accel = force / mass;
velocity += accel * dt;
position += velocity * dt;
This is the equation of motion turned into code: divide the force by the mass to get the acceleration (line 1), integrate the acceleration to get the velocity (line 2), and integrate the velocity to get the position (line 3).
There are several integration methods, and the code above is the simplest and easiest to use, the semi-implicit Euler method (English). Swapping lines 2 and 3 gives the basic Euler method, but that's not practical. Semi-implicit Euler, which updates the velocity first and immediately uses it to update the position, is vastly more usable.
Omitting mass
In this application, I decided to fix the mass at 1. That makes things easier, since there's no need to divide the force by the mass. It also removes the need to hold a mass for each one, reducing the amount of data. This makes the first line of the code above unnecessary, and the acceleration can be computed directly (conceptually it's divided by 1).
velocity += accel * dt;
position += velocity * dt;
The forces involved
So what forces act on a scrap of paper? This time I apply two forces.
- Air resistance
- Gravity
But for a point mass, there's no way to apply air resistance. It has zero size, so the air resistance should be zero. But I'll cheat and add it anyway. Let's say a brake is applied with a strength proportional to the velocity.
accel = gravity + (velocity * -resistance);
Like this. Gravity can be a constant (it does change if the distance from the Earth changes a lot, but this is confetti, after all). It's a vector like (0f, -9.81f, 0f). This time, so that it can fall in any direction you like, I don't use Unity's setting; you specify it yourself. It can even fall in the Z direction if you like.
Air resistance is made into a force by multiplying the velocity vector velocity by the resistance strength resistance. The minus sign is there because the force that arises points "opposite to the velocity".
Two options for extending it
This is about as far as simple point-mass physics can go, but frankly at this stage it doesn't look like a scrap of paper. It doesn't rotate at all; it just falls along a parabola. We need to think about what to add to make it look like a scrap of paper.
To get the motion we want, there are two options for extending it.
- Switch to rigid body physics
- Make do while keeping point-mass physics
Rigid body physics can handle rotation, so switching to it solves everything 100%. The problem is that the theory is a pain and the computation is expensive. If you use Unity's Rigidbody, you don't have to implement it yourself, but if you're thinking of eventually putting out a thousand or ten thousand scraps, placing that many GameObjects with Rigidbody components would be a bit painful.
So this time I'll take the other road. Let's make do while keeping point-mass physics. The standard way to extend point-mass physics is "add more point masses". With two, you can connect them to represent a line; with three, a triangle. Connect many and you can even represent a solid.
Let's start with the simplest, two.
Two point masses
First, prepare two positions and two velocities, and integrate them separately.
accel0 = gravity + (velocity0 * -resistance);
accel1 = gravity + (velocity1 * -resistance);
velocity0 += accel0 * dt;
velocity1 += accel1 * dt;
position0 += velocity0 * dt;
position1 += velocity1 * dt;
On its own, this is just two separate points. To get the result we want, we need to do two things.
- Maintain a relationship between the two points
- Make the forces acting on the two points different.
It would be a disaster if the two points moved separately with no relationship at all. They're two points within a single scrap of paper, so some relationship is needed.
And if the forces acting on the two points, and hence their accelerations, don't differ, both just move the same way, and there's no point in having two points. We need to set things up so that something like "one falls down quickly, while the other is slow to fall" happens.
The constraint
First, let's create the relationship.
The two points are representative points within one scrap of paper. Something like the left end and the right end. If the scrap of paper doesn't deform, "the distance between the two point masses is constant". To enforce this, instead of holding two positions we hold just one, and keep as fields the vector from point 0 to point 1 and the distance between the points. The vector represents the forward direction, so let's call it forward, and the distance is the length of the scrap, so length. Then the update looks like this.
// Generate the two points from the centre position
var position0 = position - (forward * (length * 0.5f));
var position1 = position + (forward * (length * 0.5f));
// Integrate
accel0 = gravity + (velocity0 * -resistance);
accel1 = gravity + (velocity1 * -resistance);
velocity0 += accel0 * dt;
velocity1 += accel1 * dt;
position0 += velocity0 * dt;
position1 += velocity1 * dt;
// Store the centre of the two points as the position
position = (position0 + position1) * 0.5f;
// Update forward from the difference of the two points
forward = (position1 - position0).normalized;
Since position is now the only field, the two points are generated every frame from position, forward and length. position0 and position1 are local variables, hence var.

Then, after integration, the average of the two points is stored in position, and forward is recomputed from the current positions.
Fixing the velocity that lies (the Verlet method)
If you look closely, the velocity is now lying to us. If the points were integrated independently it would be fine, but because we forcibly moved the positions to keep the distance between the two points, the velocity no longer matches.
For example, moving for 1 second at velocity 5 from x=0 gets you to x=5, but what if x is forcibly set to 4 here? The velocity says 5, but it actually only moved 4.
This state makes me uneasy (it might be fine to leave it, I'm not sure), so let's resolve it. An easy way is to change the integration to the Verlet method.
Put simply, we stop remembering the velocity. Instead, we additionally remember the previous position. The integration becomes
var newPosition = position + (position - prevPosition) + (accel * (dt * dt * 0.5f));
prevPosition = position;
position = newPosition;
(position - prevPosition) is the amount moved in one frame, so it roughly corresponds to the (velocity * dt) we had before.
This way, since we don't remember the velocity, forcibly changing the position doesn't leave things in a false state. The Verlet method has other advantages, such as stability and accuracy, but to get the most out of it you need the conditions "the time between frames is constant" and "velocity does not affect forces", and neither holds here. If you want to improve accuracy even when the time between frames varies, A Simple Time-Corrected Verlet Integration Method has a good explanation (not that I've tried it!).
Getting clever with air resistance
Next, let's make the forces on the two points differ. If the two points' positions shift relative to each other, that produces rotational motion.
Let's assume the scrap of paper is bent. And let's assume air resistance acts in the direction of the paper's normal.

If the normals differ at the two points, the air resistance on each should differ too.

The velocity vector projected onto each normal becomes the force acting on each, shown as F0 and F1 in the figure. We switched to Verlet earlier so there's no velocity vector, but let's just approximate one.
velocity0 = (position0 - prevPositon0) / dt;
That'll do. dt changes every time, so dividing by this frame's dt is a lie, but I decided not to worry about it. After all, when things are running stably it doesn't change much.
Then, assuming the normal is n,
var dot = Vector3.Dot(n, -velocity);
var accel = n * (dot * resistance);
gives us the acceleration. It's fine to leave it as is when the dot product is negative, that is, when the projection points opposite to the normal. That means air hit it from the back, and conceptually you'd flip the normal before computing the dot product, but the result is the same (if you flip n first, dot flips too, and multiplying gives the same thing).
Quaternions, to compute the normal
All that's left is the normal. But as things stand, it's a one-dimensional world of just two points, so there's no telling "which way is up". So we need to define "up for this scrap of paper". The tool for that is the quaternion.
If a quaternion variable rotation holds the orientation, the forward vector we prepared earlier comes out as
var forward = rotation * new Vector3(0f, 0f, 1f);
We no longer need to hold forward. Up and right are, respectively,
var up = rotation * new Vector3(0f, 1f, 0f);
var right = rotation * new Vector3(1f, 0f, 0f);
If the paper lies in the XZ plane and the normal is the y axis, the normal is this up. We modify it separately at the two points to represent the paper being bent. For example, if point 0's normal gets 0.1 times forward added and point 1's normal gets 0.1 times forward subtracted, the normals differ between the two points.
var up = rotation * new Vector3(0f, 1f, 0f);
var n0 = (up + (forward * 0.1f).normalized;
var n1 = (up - (forward * 0.1f).normalized;
We've generated a normal for each of the two points. This 0.1f is a tuning parameter, provided as
normalBendRatio. The bigger it is, the more it bends.
Updating the orientation
Finally, we update the orientation quaternion. To do that, we look at how forward changed between before and after the computation, generate a rotation quaternion from that, and multiply it into the current orientation to rotate it.

var newForward = (p1 - p0).normalized;
// Apply a rotation about the right vector that turns forward towards newForward
var dq = Quaternion.FromToRotation(forward, newForward);
rotation = dq * orientation; // dq is the later rotation in time, so it is farther from the vector, i.e. multiplied from the front
rotation.Normalize();
Here rotation only happens about one axis (it only rotates about the left-right axis), so looking at how forward changed is enough.
So how does it move?
It moves roughly like this.

The closer the scrap's normal is to vertical (like when it's lying on the ground), the greater the air resistance, so it slows down. When the scrap is standing upright, the air resistance is small, so gravity keeps accelerating it.
But because the normals differ at the two points, even when it's standing upright, the forces on the two points differ, and they fall at different speeds. As a result the paper rotates, gradually going from upright to lying flat.
The result is that it comes fluttering down. Depending on the balance between gravity and air resistance, it can even temporarily float upward, which is quite fun.
About wind
In this implementation you can also specify the wind strength.
When computing air resistance, the velocity is corrected by the wind strength, and air resistance is computed from the "velocity relative to the air". Varying the wind slightly for each scrap might give a nicer random feel, but if you want that, introducing mass and varying it might be cheaper.
About drawing
For drawing, doing something like "prepare a GameObject with a MeshRenderer for each scrap" would be too expensive, so this time I went ahead and optimized it.
That said, it's easy: just use the pseudo-instancing using skinning that I introduced before. I made a class called SkinnedInstancingRenderer for that article, so I'm reusing it.
That way, each scrap doesn't need its own GameObject or Transform. We have the position and the Quaternion, so we make a matrix from them and pack it into Mesh.bindposes every frame, and that's all it takes to draw them.
The code that makes the matrix looks like this.
public void GetTransform(
ref Matrix4x4 matrix,
float ZSize, // length of the paper
float XSize) // width of the paper
{
matrix.SetTRS(position, orientation, new Vector3(XSize, 1f, ZSize));
}
You just give the position, orientation quaternion and scale to Matrix4x4.SetTRS, which is easy.
About colors
This time there are 7 colors, but if each were a separate material it would slow things down. So I made a texture atlas.
I put 8 colors into a small 8x1 texture, and change the color by specifying a different UV for each scrap.

It doesn't feel much like an atlas, but this is a perfectly good atlas too.
For example, for blue, U gets (3/8)+(0.5/8)=0.4375, and V can be anything, so 0. (0.5/8) is half the width of one pixel, and adding it gives the coordinate of the center of the pixel.
In closing
What do you think? Being able to use tools like vectors, quaternions and the equations of motion widens what you can do, so personally I recommend it. On top of that, if you optimize by making good use of GPU features, you can do some fairly flashy things.
Of course, this is the Unity era, so it's also fine to leave unglamorous things like math and optimization to Unity and focus on the fun stuff yourself. As in, "just make this kind of thing with Shuriken". But by doing some of it yourself, you become able to make judgments like "someone with this kind of knowledge can make this kind of thing", or "someone who says they want to make this kind of thing but lacks this kind of knowledge is a red flag". I believe it's not entirely useless.
By the way, I came up with this "fluttering with two point masses" technique a full 17 years ago. A product I was working on at the time had an effect with feathers scattering and floating down, but the motion didn't feel physical and I didn't much like it back then, so I changed it without asking anyone. Maybe because it was less than six months after I'd joined the company straight out of school, I seem to have had a passion that baffles me even looking back now. I had a pointless obsession with changing the parameters according to how thin the air was and how strong gravity was on each stage.
One thing I didn't cover this time is "speeding up the physics computation". The behavior of a scrap of paper is fairly complex, with quite a few expensive operations such as vector normalization and quaternion-vector multiplication, so it's pretty costly. On my PC (MacBook Pro 2018), about 5000 scraps per frame is the limit. In a product I recently used it in, I kept it to 500 or fewer, considering smartphone performance.
But you want it faster, and want to put out more, don't you?
Using techniques like those advocated in DOTS (Data Oriented Technology stack), which is all the rage around Unity lately, should let us compute much faster using the CPU's spare cores. I haven't actually tried it yet, so I'm looking forward to finding out how much faster it can get myself.
