目录为:Assets/Scripts/Common/
ShakeCamera.cs
挂到一个canmera上面就能用了
using UnityEngine;
using System.Collections;
public class ShakeCamera: MonoBehaviour
{
public enum ShakeOrient
{
horizontal,
vertical,
forward,
}
public float mPeriod = 2;
public float mOffPeriod = 0;
public ShakeOrient mShakeOrient = ShakeOrient.horizontal;
public float mShakeTime = 10.0f;
public float mMaxWave = 5;
public float mMinWave = 1;
private float mCurTime = 0;
public bool mIsShake = false;
public Vector3 mDefaultPos;
public Vector3 mShakeDir;
public Transform mCamerTrans;
public Transform GetTransform()
{
if (mCamerTrans == null)
{
mCamerTrans = gameObject.transform;
}
return mCamerTrans;
}
public void ShakeScreen(ShakeOrient shakeOrient, float period, float shakeTime, float maxWave, float minWave, float offPeriod = 0)
{
if (!mIsShake)
{
if (GetTransform() == null)
{
return;
}
mShakeOrient = shakeOrient;
mPeriod = period;
mShakeTime = shakeTime;
mMaxWave = maxWave;
mMinWave = minWave;
mOffPeriod = offPeriod;
mDefaultPos = transform.localPosition;
if (shakeOrient == ShakeOrient.vertical)
{
mShakeDir = new Vector3 (0, 1, 0);
}
else if (shakeOrient == ShakeOrient.forward)
{
mShakeDir = mCamerTrans.forward;
}
else if (shakeOrient == ShakeOrient.horizontal)
{
Vector3 v1 = new Vector3 (0, 1, 0);
Vector3 v2 = mCamerTrans.forward;
mShakeDir = Vector3.Cross (v1, v2);
mShakeDir.Normalize ();
}
mIsShake = true;
}
}
public void Update()
{
if (mIsShake)
{
float factor = mCurTime / mShakeTime;
float totalPeriod = mPeriod * Mathf.PI;
float maxValue = mMaxWave - (mMaxWave - mMinWave) * factor;
float radValue = mOffPeriod * Mathf.PI + factor * totalPeriod;
float value = maxValue * Mathf.Sin (radValue);
if (mShakeOrient == ShakeOrient.vertical)
{
transform.localPosition =
new Vector3 (transform.localPosition.x, mDefaultPos.y, transform.localPosition.z)
+ mShakeDir * value;
}
else
{
transform.localPosition = mDefaultPos + mShakeDir * value;
}
mCurTime += Time.deltaTime;
if (mCurTime > mShakeTime)
{
mIsShake = false;
mCurTime = 0;
}
}
}
void OnGUI()
{
if (GUI.Button(new Rect(10, 10, 150, 100), "Shake!"))
{
ShakeScreen (mShakeOrient, mPeriod, mShakeTime, mMaxWave, mMinWave, mOffPeriod);
mIsShake = true;
mDefaultPos = transform.localPosition;
}
}
}