Unity爆炸加螢幕震動效果
首先是震動的程式碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shake : MonoBehaviour {
private float shakeTime = 0.0f;
private float fps = 20.0f;
private float frameTime = 0.0f;
private float shakeDelta = 0.005f;
public Camera cam;
public bool isshakeCamera = false;
// Use this for initialization
void Start()
{
shakeTime = 2.0f;
fps = 20.0f;
frameTime = 0.03f;
shakeDelta = 0.005f;
// isshakeCamera=true;
}
// Update is called once per frame
void Update()
{
if (isshakeCamera)
{
if (shakeTime > 0)
{
shakeTime -= Time.deltaTime;
if (shakeTime <= 0)
{
cam.rect = new Rect(0.0f, 0.0f, 10.0f, 10.0f);
isshakeCamera = false;
shakeTime = 1.0f;
fps = 20.0f;
frameTime = 0.03f;
shakeDelta = 0.005f;
}
else
{
frameTime += Time.deltaTime;
if (frameTime > 1.0 / fps)
{
frameTime = 0;
cam.rect = new Rect(shakeDelta * (-1.0f + 2.0f * Random.value), shakeDelta * (-1.0f + 2.0f * Random.value), 1.0f, 1.0f);
}
}
}
}
}
}
觸發爆炸的程式碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenShake : MonoBehaviour {
public GameObject gameObject;
public Camera myCra;
void Start()
{
}
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "ball")
{
gameObject.SetActive(true);
myCra.GetComponent<Shake>().isshakeCamera = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.transform.tag == "ball")
{
gameObject.SetActive(false);
myCra.GetComponent<Shake>().isshakeCamera = false;
}
}
}
實力效果:
只是舉了一個簡單的例子,但是你們可以把它新增到子彈上面或者其他觸發事件上。下一篇我會把CF中的換槍寫一下。
比如可以用我上次寫的物件池,把今天的內容新增上去: