Come se fossi

## Unity 2D [ E2 ] - Apply the effect vibration / earthquake to a sprite The effect of shake , vibration or earthquake is easily implemented using some methods such as Random.insideUnitCircle that generates randomly a point on a circle of radius 1 .

It is therefore easily applicable to a sprite especially in 2D environment . Whereas the generation of a point randomico in a circle , having the center coordinates 0x , 0y we can easily apply a force to multiply the "power" then the radius of action. Suppose you've got a point random " Random Point 1 " Coordinate ( example) -0.5x and -0.6y to which we apply a constant , called the shake strength but in essence it is an increase in the radius for example, force 2 .

So we will have a new location (environment 2d ) with coordinates :

Vector3.x = random.x * force
Vector3.y = random.y *
force
Vector3.z = z_original

Having said that, we can create a script that cycle on and off the shake , vibration or earthquake , if you prefer , where the force is parameterized as input parameter . This script is applicable to the sprite on which you want to act .

using UnityEngine;
using System.Collections;

public class ShakeEffect : MonoBehaviour {

// vars
private bool shakeOn = false;
private float shakePower = 0;

// sprite original position
private Vector3 originPosition;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

// if shake is enabled
if(shakeOn) {

// reset original position
transform.position = originPosition;

// generate random position in a 1 unit circle and add power
Vector2 ShakePos = Random.insideUnitCircle * shakePower;

// transform to new position adding the new coordinates
transform.position = new Vector3 (transform.position.x + ShakePos.x, transform.position.y + ShakePos.y, transform.position.z);
}
}

// shake on
public void ShakeCameraOn(float sPower){

//save position before start shake,
//this it's really important otherwise
//the sprite can goes away and will not return
//in native position
originPosition = transform.position;

//enable shaking and setting power
shakeOn = true;
shakePower = sPower;
}

// shake off
public void ShakeCameraOff(){

// shake off
shakeOn = false;

// set original position after
transform.position = originPosition;
}

}


di GuiZ
06/04/2016

### Commenta

We'll never share your email with anyone else.