- Unity Artificial Intelligence Programming
- Dr. Davide Aversa Aung Sithu Kyaw Clifford Peters
- 300字
- 2021-06-10 18:57:49
The Bullet class
Next, we set up our Bullet prefab with two orthogonal planes using a laser-like material and a Particles/Additive property in the Shader field:
The code in the Bullet.cs file is as follows:
using UnityEngine; using System.Collections; public class Bullet : MonoBehaviour { //Explosion Effect
[SerializeField] private GameObject Explosion;
[SerializeField]
private float Speed = 600.0f;
[SerializeField]
private float LifeTime = 3.0f;
public int damage = 50; void Start() { Destroy(gameObject, LifeTime); } void Update() { transform.position += transform.forward * Speed * Time.deltaTime; } void OnCollisionEnter(Collision collision) { ContactPoint contact = collision.contacts[0]; Instantiate(Explosion, contact.point, Quaternion.identity); Destroy(gameObject); } }
Our Bullet has three properties: damage, Speed, and Lifetime—the latter so that the bullet will be automatically destroyed after a certain amount of time. Note that we use [SerializeField] to show the private fields in the inspector; by defult, in fact, Unity only shows public fields. It is a good practice to set as public only fields that are used in other classes.
As you can see, the Explosion property of the bullet is linked to the ParticleExplosion prefab, which we're not going to discuss in detail. There's a prefab called ParticleExplosion under the ParticleEffects folder. We just drop that prefab into this field. This particle effect is played when the bullet hits something, as described in the OnCollisionEnter method. The ParticleExplosion prefab uses a script called AutoDestruct to destroy the Explosion object automatically after a small amount of time.
using UnityEngine;
public class AutoDestruct : MonoBehaviour
{
[SerializeField]
private float DestructTime = 2.0f;
void Start()
{
Destroy(gameObject, DestructTime);
}
}
The AutoDestruct is a small but convenient script. It just destroys the attached object after a certain amount of seconds. Unity games use a similar script almost every time for many situations.
- 社交網絡對齊
- GPS/GNSS原理與應用(第3版)
- 重新定義Spring Cloud實戰
- Building RESTful Web Services with Spring 5(Second Edition)
- 互聯網安全的40個智慧洞見:2015年中國互聯網安全大會文集
- Yii Application Development Cookbook(Second Edition)
- 雷達饋線技術
- 城域網與廣域網(第2版)
- 數字調制解調技術的MATLAB與FPGA實現:Altera/Verilog版(第2版)
- INSTANT KineticJS Starter
- 深入理解OpenStack Neutron
- Practical Web Penetration Testing
- 互聯網安全的40個智慧洞見(2016)
- LwIP應用開發實戰指南:基于STM32
- 工業以太網技術:AFDX/TTE網絡原理、接口、互連與安全