7-particle explosion with Android

Source: Internet
Author: User
Tags bitwise operators

Do you want to know how to create an explosion? Let's copy a short path and try to achieve a basic example explosion.

Explosion is a pile of particles dispersed on the screen. For simplicity, we think that all examples come from a point.

Think about fireworks. A small rocket rises and then explodes into a hundred stars, and eventually disappears when it falls.

To make it simple, we will make some particles, and we will place them in a single position to give them random power. This value is a vector value, that is, it has both directions and sizes. The size determines the speed, and the direction determines the particle direction.

Particle

Class File

public class Particle {public static final int STATE_ALIVE = 0;// particle is alivepublic static final int STATE_DEAD = 1;// particle is deadpublic static final int DEFAULT_LIFETIME = 200;// play with thispublic static final int MAX_DIMENSION= 5;// the maximum width or heightpublic static final int MAX_SPEED= 10;// maximum speed (per update)private int state;// particle is alive or deadprivate float width;// width of the particleprivate float height;// height of the particleprivate float x, y;// horizontal and vertical positionprivate double xv, yv;// vertical and horizontal velocityprivate int age;// current age of the particleprivate int lifetime;// particle dies when it reaches this valueprivate int color;// the color of the particleprivate Paint paint;// internal use to avoid instantiation}

A particle is just a small rectangle with some attributes. It can also be an image, a circle, or other shapes.

It has a state, indicating that the particle is still dead. A particle is alive. When its color is not black, its age is not yet reached. I will read it in detail later.

It has a position, which is a 2D Coordinate Position, represented by X and Y in the system.

There is also a velocity and direction. The velocity is a vector, so it has two elements in a 2D environment. There will be a Z element in 3D. Now we are still in 2D. For simplicity, we should first have two attributes.

The particle is 0 at the beginning of age, and each function update will increase.

Lifetime is the largest age before a particle crashes.

Others are colors and brushes, which are used for drawing.

Recalling previous records, game updates only call the update functions of each entity and display them. The particle update method is quite simple.

First, create a particle.

public Particle(int x, int y) {this.x = x;this.y = y;this.state = Particle.STATE_ALIVE;this.widht = rndInt(1, MAX_DIMENSION);this.height = this.widht;this.lifetime = DEFAULT_LIFETIME;this.age = 0;this.xv = (rndDbl(0, MAX_SPEED * 2) - MAX_SPEED);this.yv = (rndDbl(0, MAX_SPEED * 2) - MAX_SPEED);// smoothing out the diagonal speedif (xv * xv + yv * yv > MAX_SPEED * MAX_SPEED) {xv *= 0.7;yv *= 0.7;}this.color = Color.argb(255, rndInt(0, 255), rndInt(0, 255), rndInt(0, 255));this.paint = new Paint(this.color);}

It is intuitive to check the particle creation process.

The particle is created at position X and Y.

The status is set to alive

We need to randomize the size of the rectangle, because the explosion creates particles with different sizes and shapes, we just random the size and color.

I wrote some help methods to generate random numbers. Please refer to the complete code

The next step is to set the life time. Each particle has the same life time.

The particle age at birth is 0.

Next is the interesting bit. It's very amateurish. To set the speed I have used 2 random numbers for the 2 components of the speed vector (VXAndVy). The Smoothing is needed because if both components are near the maximum value then
Resulting magnindexing will be over the max speed. You cocould use simple trigonometric functions with a random degree instead of this.

The next step is interesting, very amateur. To set the speed, I used two random numbers to express the two elements of the velocity vector, VX and Vy.

The last step is to set the color, which is also random.

There you have it.

Particle update function

public void update() {if (this.state != STATE_DEAD) {this.x += this.xv;this.y += this.yv;// extract alphaint a = this.color >>> 24;a -= 2; // fade by 2if (a <= 0) { // if reached transparency kill the particlethis.state = STATE_DEAD;} else {this.color = (this.color & 0x00ffffff) + (a << 24);// set the new alphathis.paint.setAlpha(a);this.age++; // increase the age of the particle}if (this.age >= this.lifetime) {// reached the end if its lifethis.state = STATE_DEAD;    }}}

It is quite simple. Each update, the position is set based on the speed, and the Alpha value of the particle color is gradually reduced. In other words, the particle gradually fades.

If the age exceeds the life value or the opacity is 0, it means that the particle is completely transparent, which means the end of life.

If you wonder about the magic with colours, it is quite simple once you get the bitwise operators. don't worry, I'm rubbish as well, just make sure you know where to look. here is a good explanation of color components and how to use bitwise operators
Manipulate them:
Http://lab.polygonal.de/2007/05/10/bitwise-gems-fast-integer-math. It's faster than using the objects but you can safely use the android methods too.

If you want to know the mysteries of color, it is too easy to understand bitwise calculation. Don't worry, I don't understand it. Here is a very good explanation of color, how to Use bitwise operations to control them?

 

Edge note of color

In Android, the color is integer. If you know RGB and argb, it would be great. RGB is 24 bits, and argb is 32 bits with an Alpha value, indicates transparency or opacity.

Opacity values: 0 = transparent, 255 = completely opaque.

Opacity. 0 is transparent and 255 is completely transparent.

To represent hexadecimal, you can add a prefix 0x. It is very easy to represent the color in hexadecimal notation. For example, 0x00ff00 indicates green, and the pattern is 0 xrrggbb (red, green, blue ). The Alpha value is 0 xw.rggbb.

Because it is in hexadecimal notation, the value is between 00 and FF, 0 is 0, and FF is 255 of the 10 hexadecimal notation.

The following describes how to extract values from colors.

int color = 0xff336699;int alpha = color >>> 24;int red   = color >>> 16 & 0xFF;int green = color >>>  8 & 0xFF;int blue  = color & 0xFF;

The painting method is also very simple.

public void draw(Canvas canvas) {paint.setColor(this.color);canvas.drawRect(this.x, this.y, this.x + this.widht, this.y + this.height, paint);}

This step is to create a lot of particles on the drawing board and observe the phenomenon.

The explosion

Explosion is an explosion of hundreds of examples from the origin.

Explosion

In the image above you see the first 4 updates of a simple explosion. All the participants have the same speed but they spread out in different directions. Each circle is one update.

The main properties of an explosion are:

public class Explosion {public static final int STATE_ALIVE = 0;// at least 1 particle is alivepublic static final int STATE_DEAD = 1;// all particles are deadprivate Particle[] particles;// particles in the explosionprivate int x, y;// the explosion's originprivate int size;// number of particlesprivate int state;// whether it's still active or not}

It contains an array of particles. The size is the number of particles. An explosion is alive if it has at least one particle alive.

TheupdateIs extremely simple. It iterates through all the participants and calltheupdate()Method on each particle.
draw()Ditto.

In our application we will create explosions on the screen where we touch it.
The constructor is very simple:

public Explosion(int particleNr, int x, int y) {Log.d(TAG, "Explosion created at " + x + "," + y);this.state = STATE_ALIVE;this.particles = new Particle[particleNr]; for (int i = 0; i < this.particles.length; i++) {Particle p = new Particle(x, y);this.particles[i] = p;} this.size = particleNr;}

The array of particles is being filled at the touch down position.

In our application we will allow up to 10 explosions. So inMainGamePanelWe declare an array of explosions.

private Explosion[] explosions;

InsurfaceCreatedMethod We instantiate the array and fill itnull.

explosions = new Explosion[10];for (int i = 0; i < explosions.length; i++) {explosions[i] = null;}

TheonTouchEventIs where we create explosions.

public boolean onTouchEvent(MotionEvent event) {if (event.getAction() == MotionEvent.ACTION_DOWN) {// check if explosion is null or if it is still activeint currentExplosion = 0;Explosion explosion = explosions[currentExplosion];while (explosion != null && explosion.isAlive() && currentExplosion < explosions.length) {currentExplosion++;explosion = explosions[currentExplosion];}if (explosion == null || explosion.isDead()) {explosion = new Explosion(EXPLOSION_SIZE, (int)event.getX(), (int)event.getY());explosions[currentExplosion] = explosion;}}return true;}

What we do is iterate through the explosions and when we find the first
null
(This means we never used it for an instance) or the first dead explosion we create a new one at the touch position.

TheupdateAndrenderMethods are straight forward. iterate through the explosions and if they are not null and are alive then call their update and draw methods respectively.

In the final code I added a border for the screen as the wall and added a basic collision detection for the participant so they bounce off the Wils. the wall is being transmitted as a reference and the update method checks for collision with it. use it
An exercise and remove the collision and try attaching an image to the particle instead of being a rectangle. To create explosions just click on the screen.

It shoshould look like this:

Explosion screenshot

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.