Unity 实现物体破碎效果(转)

感谢网友分享,原文地址(How to Make an Object Shatter Into Smaller Fragments in Unity),中文翻译地址(Unity实现物体破碎效果)

In this tutorial I will show you how to create a simple shattering effect for your Unity game. Instead of just "deleting" a crate (or any other object) when it is hit or destroyed, we can make it splinter into smaller pieces.

For this tutorial, you'll need the newest version of Unity, and some basic experience with it. For the more advanced effect later in the tutorial, a 3D modelling tool will also be necessary. If you don't have one available or don't want to model the objects yourself, I've included them in the source downloads. (The Unity files themselves are also available there.)

In the basic version of this effect, a cube will be destroyed, leaving several fragments in its wake which will fall realistically to the ground:

splintering_02_cube_intactsplintering_03_cube_broken

Later, we'll switch the cube for a more complicated barrel model:

splintering_04_barrel_intactsplintering_05_barrel_broken

You can try it out for yourself here:

barrel_demo_screenshot

 

Click to try the demo. (The cube demo is available here, too.)

Create a new Unity project and open a fresh scene. Create a plane, which will act as our ground, and a cube, which will be the destructible object. Also, place a directional light to make things more visible. Create two new materials and assign them to the floor and the cube, so that we can tell them apart, and move the camera so that everything can be seen:

splintering_01_setup

There are many ways to "destroy" the cube. For now, we'll take the simplest approach possible.

Create a new JavaScript file and name it destructionController.js. In this, we'll put all the functionality of removing the cube and creating the fragments. Add the following lines to it:

1
2
3
4
5
6
7
function Update()
 {
     if(Input.GetKey(Keycode.space))
     {
         Destroy(gameObject);
     }
 }

Now, add the script to the cube by dragging it onto it. Start the game and make a test run. If you press space, the cube should be deleted.

splintering_06_cube_deleted

After being removed, it will also no longer appear in the hierarchy, as you can see in the screenshot.

Now create eight smaller cubes; these will be the "fragments" of the current cube. Give them the same material as the cube. (Don't worry about the looks yet, we'll make them look awesome later on.) They should look like this:

splintering_07_fragments_01

Stack all 8 cubes to form a bigger, single cube, without them intersecting:

splintering_07_fragments_02

Give every cube a rigidbody, set their mass to 22, activate use gravity, and deactivateis kinematic. This will make the fragments fall down and use physics. If you want, you can tweak these values later to produce results that are better suited for your game.

splintering_09_fragments_04

Now, group the cubes under a new empty gameObject and call it remainsCube. When the original cube is destroyed, it will be replaced with this new object made out of smaller cubes.

splintering_08_fragments_03

Drag the remainsCube object into the project folder to make a prefab out of it. Once it is safely in the prefab folder, delete it out of the main scene, and it is ready to use.

Add the highlighted lines to the destructionController script:

1
2
3
4
5
6
7
8
9
var remains: GameObject;
function Update()
{
    if(Input.GetKey(Keycode.space))
    {
        Instantiate(remains, transform.position, transform.rotation);
        Destroy(gameObject);
    }
}

This will create a copy of the remains at the exact position of the cube. Afterwards, the cube will be removed, giving the illusion that the new one is actually the old one, but "broken".

To actually get this to work, you have to manually assign the remains to the cube. Click on it, and in the Inspector you should see a tab containing the Destruction Controllerscript. There should be a slot called Remains, which should currently be empty. Drag the remains prefab from the project folder into this slot. The Destruction Controllerscript in the Inspector should now look like this:

splintering_16_prefab_assign

Make a test run! If everything is set up correctly, then when you press space, the remains should replace the cube. If you're lucky, they should then tumble to the ground.

So, this basic cube:

splintering_02_cube_intact

...should turn into something similar to this:

splintering_10_unlucky

Sadly, it is not guaranteed that the fragments will tumble in a nice way. Fortunately, there are ways to solve that.

Create a new empty gameObject and give it a sphere collider, but no rigidbody. Pull the remains into the scene, so that you can edit them. Add the sphere collider object to the remains, and place it so that it intersects with some of the cubes:

splintering_17_sphere

Now, the fragments will immediately collide with the sphere, creating a tumble effect:

splintering_02_cube_intactsplintering_11_better

Depending on the game you are building, we can't afford too many "splinters" at once in a scene. The straightforward solution is to delete them after a few seconds. In order to do so, create a new JavaScript file and name it selfDestruct.js. Put the following code in it:

1
2
3
4
5
function Start()
{
    yield WaitForSeconds(4.0);
    Destroy(gameObject);
}

When the object is created, it will wait for four seconds, and then delete itself. Add this code to the remains object. If you now destroy the cube and create the fragments, the remains will destroy themselves after four seconds.

And that's it! Now you have the basics to efficiently have an object "shatter" into several smaller pieces when it is destroyed. You can use this effect as-is, but let's take it a little further and see how to use it with a more complex object.

Now that we've got the basic system in place, we can make it more pretty by replacing the cubes with actual objects.

splintering_05_barrel_broken

If you are adept in a 3D modelling tool, you can create your own objects. If not, or if you do not have one available, you can get the prepared 3D file from the source download.

Copy the file into your asset folder, and the 3D models will automatically be imported for your use. Before using them, click the file in the Asset Explorer and make sure that the source files are being imported correctly at a scale factor of 1 (not 0.1 or 0.001; that only complicates things).

splintering_12_importer

If you look at the objects, you can see a field called meshfilter in the Inspector. If you click it, you get a list of all available meshes in the project. Now replace all the cubes in the Cube remains with barrel parts.

splintering_13_barrel_01

The intact cube gets the barrel mesh; the smaller cube fragments need the meshesbarrel_fragment_01 to barrel_fragment_08. After those are assigned, set their local positions to (0, 0, 0). (Their pivot-points have been set so that they can be easily zeroed in that way.)

Instead of a box collider, a mesh collider would be much more convenient. Remove all the box colliders on the fragments, and replace them with mesh colliders. Check each mesh collider and make sure each has the correct mesh applied (that is,barrel_fragment_01 needs the barrel_fragment_01 mesh, and so on).

splintering_15_barrel_03

Once that is done, set all mesh colliders to convex. (A non-convex mesh collider can't collide with other non-convex mesh colliders. It's a programming thing.) Also, remove the sphere collider we added to the remains, as it might not be necessary.

It everything is set up correctly, you should have a barrel which will spring apart into eight smaller pieces.

The same system can also be used to add other effects to the destruction. Do you have an explosion? Add it to the remains! Add sounds, for a satisfying crack. Put a particle effect in there, creating a small puff of smoke.

In this tutorial I've showed you the most straightforward way of making an object shatter into smaller fragments. Now you know how to destroy an object, removing it from the game; how to swap the object with smaller fragments directly before its destruction; and how to have the fragments self-destruct afterwards.

This system can now be modified and adapted to fit many specific purposes. You could have a crate or a barrel splinter and shatter when shot. You could create an explosion after a plane is hit. Or you could have a boat crack into two pieces. Enjoy!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/401230.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

CC254x--OSAL

OSAL运行原理 蓝牙协议栈PROFILE、所有的应用程序、驱动等都是围绕着OSAL组织运行的。OSAL(Operating System Abstraction Layer)操作系统抽象层,它不是一个真正的操作系统(它没有 Context Switch 上下文切换功能)&am…

mysql跨节点join——federated引擎

一、 什么是federated引擎 mysql中的federated类似于oracle中的dblink。 federated是一个专门针对远程数据库的实现,一般情况下在本地数据库中建表会在数据库目录中生成相对应的表定义文件,并同时生成相对应的数据文件。 [图] 但是通过federated引擎创建…

【阅读SpringMVC源码】手把手带你debug验证SpringMVC执行流程

Python微信订餐小程序课程视频 https://edu.csdn.net/course/detail/36074 Python实战量化交易理财系统 https://edu.csdn.net/course/detail/35475 ✿ 阅读源码思路: 先跳过非重点,深入每个方法,进入的时候可以把整个可以理一下方法的执…

Zabbix监控(十六):分布式监控-Zabbix Proxy

说明:Zabbix支持分布式监控,利用Proxy代理功能,在其他网络环境中部署代理服务器,将监控数据汇总到Zabbix主服务器,实现多网络的分布式监控,集中监控。1、分布式监控原理Zabbix proxy和Zabbix server一样&am…

CC254x--BLE

BLE协议栈 BLE体系结构,着重了解GAP和GATT。 PHY物理层在2.4GHz的ISM频段中跳频识别。LL连接层:控制设备的状态。设备可能有5中状态:就绪standby,广播advertising,搜索scanning,初始化initiating和连接con…

Azure Container App(一)应用介绍

Python微信订餐小程序课程视频 https://edu.csdn.net/course/detail/36074 Python实战量化交易理财系统 https://edu.csdn.net/course/detail/35475 一,引言 容器技术正日益成为打包、部署应用程序的第一选择。Azure 提供了许多使用容器的选项。例如&#xff0…

怎样配置键盘最方便,以及一些设计的思考

使用Emacs的人,如果肯折腾,肯定有重新映射键盘的经历。我原来经常看到的是把Ctrl和Capslock交换,但是我感觉没什么道理,因为Ctrl已经用的很熟练了,换了反而不方便,而且对其他程序影响太大。那么我们就要使用…

profile、服务、特征、属性之间的关系

一个profile有很多的服务,一个服务又有很多的特性,一个特性中又有几种属性条目组成。 profile(数据配置文件) 一个profile文件可以包含一个或者多个服务,一个profile文件包含需要的服务的信息或者为对等设备如何交互的…

机器学习实战 | SKLearn最全应用指南

Python微信订餐小程序课程视频 https://edu.csdn.net/course/detail/36074 Python实战量化交易理财系统 https://edu.csdn.net/course/detail/35475 作者:韩信子ShowMeAI 教程地址:http://www.showmeai.tech/tutorials/41 本文地址:http…

Scheme语言入门

2019独角兽企业重金招聘Python工程师标准>>> Scheme语言入门 最早听说 LISP,是 Stallman 的 GNU Emacs 中将 LISP 作为嵌入语言,定制和增强 Emacs。GNU Emacs 是一个文本编辑器,文本就是一种符号,而 Lisp 正好就是针对…

如何将docker 镜像上传到docker hub仓库

Python微信订餐小程序课程视频 https://edu.csdn.net/course/detail/36074 Python实战量化交易理财系统 https://edu.csdn.net/course/detail/35475 如何将docker 镜像上传到docker hub仓库 目录* 如何将docker 镜像上传到docker hub仓库 背景 1.注册docker hub账号 2.…

ThinkPHP框架 _ 学习3

【路由解析】 通过url地址get参数找到指定的控制器,并进行对应方法调用请求 http://网址/index.php?m模块名称&c控制器&a方法 以上url地址信息代码不够优雅、不安全。 tp框架url地址可以由以下四种 http://网址/index.php?mXX&cXX&aXX 基本get模…

The slave I/O thread stops(equal MySQL server ids)

在学习replication时遇到了如下问题:显然看到Slave_IO_Running 为NO 表示有问题;到日志里查看,错误如下:position 98100121 17:09:03 [ERROR] The slave I/O thread stops because master and slave have equal MySQL server ids;…

pytest配置文件pytest.ini

Python微信订餐小程序课程视频 https://edu.csdn.net/course/detail/36074 Python实战量化交易理财系统 https://edu.csdn.net/course/detail/35475 说明: pytest.ini是pytest的全局配置文件,一般放在项目的根目录下是一个固定的文件-pytest.ini可以…

基于积分墙盈利模式的APP架构思考

基于积分墙盈利模式的APP架构思考from: http://kuailiyu.cyzone.cn/article/4156.html个人感言:一款小游戏好不容易辛辛苦苦开发出来,但是在后期如何不注重推荐,其下场可想而知。而个人游戏开发者的产品很难实现应用内付费集成,技…

【死磕NIO】— 探索 SocketChannel 的核心原理

Python微信订餐小程序课程视频 https://edu.csdn.net/course/detail/36074 Python实战量化交易理财系统 https://edu.csdn.net/course/detail/35475 大家好,我是大明哥,一个专注于【死磕 Java】系列创作的程序员。 【死磕 Java 】系列为作者「chenssy…

session的存储方式

1、保存在IIS进程中 2、保存在StateServer上 3、保存在SQL Server数据库中 转载于:https://www.cnblogs.com/dashi/archive/2012/10/10/4034799.html

PixiJS - 基于 WebGL 的超快 HTML5 2D 渲染引擎

Pixi.js 是一个开源的HTML5 2D 渲染引擎,使用 WebGL 实现,不支持的浏览器会自动降低到 Canvas 实现。PixiJS 的目标是提供一个快速且轻量级的2D库,并能兼容所有设备。此外,让开发者无需了解WebGL,就可以感受到硬件加速…

腾讯的老照片修复算法,我把它搬到网上,随便玩

Python微信订餐小程序课程视频 https://edu.csdn.net/course/detail/36074 Python实战量化交易理财系统 https://edu.csdn.net/course/detail/35475 大家好,之前向大家介绍并跑通了腾讯开源的老照片修复算法(AI 黑科技,老照片修复&#xf…