Sunday, July 5, 2015

Water fall animation using Particle System

Water falling is a cool piece of animation in iOS apps. I had to use particle system to create an animation where water hose is spraying water. Think of the real water hose.

1. You have a continuous flow of water which are collection of water drops. 
2. The shape in which water falls (you may have seen the settings on the hose - shower, mist, full etc).

The above two concepts translate exactly to the concepts of emitter cell and an emitter layer.




There is one more thing: 

In the real world, water will always fall down because of gravity. But in programming world water direction need to be controlled. This is controlled by a property called emissionLongitude.






The complete code is checked into https://github.com/cspnanda/ParticleSystem
Official apple API docs are here and here

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Initialize the Emitter Cell. drop is a simple picture of water. From apple doc
// A layer can set this property to a CGImageRef to display the image as its contents.

    CAEmitterCell *emitterCell = [CAEmitterCell emitterCell];
    emitterCell.contents = (id) [[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"drop" ofType:@"png"]] CGImage];

    // Define the velocity range - The amount by which the velocity of the cell can vary. 
    emitterCell.velocityRange = 1;

    // The angle in which water will fall
    emitterCell.emissionRange = M_PI_2;

    // Set the x and y component of an acceleration vector
    emitterCell.xAcceleration=-10;
    emitterCell.yAcceleration=300;

    // Set the emissionLongitude
    emitterCell.emissionLongitude = longitude;


// Constructing emitterLayer

// Initialize the Layer
emitterLayer = (CAEmitterLayer *) self.layer;
// Set the emitter cell as part of emitterLayerContents
emitterLayer.emitterCells = [NSArray arrayWithObject: emitterCell];

// Add the emitter Layer to main view
[self.view addSubview:waterFall];

Voila. Now when you compile the code and run, you should see water hose spraying water.

Let us look at two properties of emitter cell. xAcceleration and yAcceleration. As the name xAcceleration is how the water travels in X axis and yAcceleration is how water travels in Y axis. In the segment control when we set the yAcceleration to 0 we see no particles fall in Y axis.

1 comment: