目录
1,前期准备
2,具体实现
3,实例代码
1,前期准备
使用blender制作模型和导入粒子包
一,模型制作
打开blender,删除灯光和摄像头,只保留方块
将其作为未破坏方块模型,并以.fbx格式导出
完成未破坏方块模型之后,编辑 ——》》偏好设置 ——》》插件,搜索Object Cell Fracture插件,安装此插件
返回场景,点击方块,然后物体 ——》》快速效果 ——》》Cell Fracture
应用效果之后,方块呈碎裂状
删除Cube并保存为已被破坏方块模型
二,导入粒子包
从Unity商店中搜索Particle Pack并导入
2,具体实现
一,爆破效果实现
爆破效果分为力的效果和火花粒子效果。
力的效果指,当炸弹爆炸的时候,在一个固定半径内,给周围的物体,施加一个以球心为点向外的力。
为了实现这个效果,首先必须给相关模型添加刚体(Rigidbody),这样模型就能受到力的影响了
然后使用Rigidbody类的AddExplosionForce()方法,实现在固定半径施加力的效果,这样的力的效果就完成,接下来就差火花粒子效果
火花粒子效果指当爆炸发生时迸发出的火花效果,这个效果可以使用Instantiate方法调用之前导入的粒子包中的爆炸效果来实现(注意:一定要把效果的Looping选项关闭,否则爆炸效果会多次循环)
二,模型破碎效果实现
模型破碎效果是指方块遭到爆破后模型破碎,这个效果,可以利用Instantiate和Destroy方法在爆破的一瞬间将原有模型销毁替换成破碎模型
3,实例代码
代码如下
Boob.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Boob : MonoBehaviour
{
// Start is called before the first frame update
public float timer = 4.0f;
private float boom_time;
public GameObject explosioneffect;
private bool boom_state = false;
public float radius = 5f;
public float force = 700f;
void Start()
{
boom_time = timer;
}
// Update is called once per frame
void Update()
{
boom_time -= Time.deltaTime;
if(boom_time <= 0f&&!boom_state)
{
Explosion();
boom_state = true;
}
}
private void Explosion()
{
Debug.Log("BooMMM");
Instantiate(explosioneffect, transform.position, transform.rotation);
Collider[] colliders = Physics.OverlapSphere(transform.position, radius);
foreach(Collider nearbyObject in colliders)
{
Rigidbody rb = nearbyObject.GetComponent<Rigidbody>();
if(rb!=null)
{
rb.AddExplosionForce(force, transform.position,radius);
}
Debris dest = nearbyObject.GetComponent<Debris>();
if(dest!=null)
{
dest.OnDestroy();
}
}
Collider[] collidersToMove = Physics.OverlapSphere(transform.position, radius);
foreach(Collider nearbyObject in collidersToMove)
{
Rigidbody rb = nearbyObject.GetComponent<Rigidbody>();
if(rb!=null)
{
rb.AddExplosionForce(force, transform.position, radius);
}
}
Destroy(gameObject);
}
}
Debris .cs
public class Debris : MonoBehaviour
{
// Start is called before the first frame update
public GameObject Explosive_debris;
public void OnDestroy()
{
Instantiate(Explosive_debris, transform.position, transform.rotation);
Destroy(gameObject);
}
}
最终效果如下图