Bouncy Particles

I decided to have some fun with Unity tonight so I’ve been having fun rendering to a Texture2D some particles bouncing around with an eye towards making a 2D fluid simulation.

It took most of the night wrestling with Unity’s Texture2D class to even get it to render anything in the first place.

Once that was tamed, the particles themselves were easy!

class SimulatedParticle {
	public Vector2 position;
	public Vector2 velocity;
	float gravityConstant = -1;
	int boundaryX;
	int boundaryY;
	float drag = -0.5f;
	public SimulatedParticle (int width, int height) {
		position = new Vector2(Random.Range(0, width), Random.Range(0, height));
		velocity = Vector2.zero;
		velocity.x = Random.Range(-1, 1);

		boundaryX = width;
		boundaryY = height;
	}

	public void Move() {
		velocity.y += gravityConstant;

		position.x += velocity.x;
		position.y += velocity.y;

		// If we hit the sides, bounce back
		if (position.x < 0) velocity.x = -velocity.x + drag;
		if (position.x > boundaryX) velocity.x = -velocity.x + drag;

		// if we hit the top or bottom, bounce back
		if (position.y < 0) velocity.y = -velocity.y + drag;
		if (position.y > boundaryY) velocity.y = -position.y + drag;
	}
}

I rendered out the colour based on the velocity of the particle. It defaults to green fully on. The velocity affects the red and blue channels.

// render the particle's current position
renderTexture.SetPixel(
	(int) particle.position.x,
	(int) particle.position.y,
	new Color(
		Mathf.Abs(particle.velocity.y),
		1,
		Mathf.Abs(particle.velocity.x)
	)
);

Right now it’s late and I have to go to bed, but this is interesting. I’ll continue to play with this idea later.

I created a GitHub Repository that you can check out. https://github.com/lilithebowman/Fluid-Simulation-Experiments

By Lilithe

Dork.