Unity3D坦克大战3(武器系统)

来源:互联网 发布:小说阅读软件下载 编辑:程序博客网 时间:2024/05/02 01:51

以下代码都是在tank下的,新建C#,命名为tankweapon.cs


1.实例化炮弹

将炮弹设置为 异物体 

通过public来建立对象,在环境中拖动具体事物来建立对应关系。有点图形化编程的意思。

实例化炮弹的代码(给tank),注意体会有趣的怪现象。

using UnityEngine;using System.Collections;public class tankweapon : MonoBehaviour {public GameObject shell;//炮弹的实体public float shootPower;public Transform shootPoint;//炮弹的起始发射位置void Update () {if(Input.GetKeyDown(KeyCode.Space)){//fireshoot();}}void shoot(){Instantiate(shell, shootPoint.position, shootPoint.rotation);//实例化炮弹}}

2.发射炮弹:增加力 / 增加初速度

using UnityEngine;using System.Collections;public class tankweapon : MonoBehaviour {public GameObject shell;//炮弹的实体public float shootPower;public Transform shootPoint;//炮弹的起始发射位置void Update () {if(Input.GetKeyDown(KeyCode.Space)){//fireshoot();}}void shoot(){GameObject newShell = Instantiate(shell, shootPoint.position, shootPoint.rotation) as GameObject; //实例化炮弹,as类型转化Rigidbody r = newShell.GetComponent<Rigidbody>();//实物体r.velocity = shootPoint.forward * shootPower;//设置炮弹速度}}

3.增加简易火焰效果

在shell中添加pointlight,设置颜色后保存(拖动覆盖,字体变蓝)。


4.添加发射炮弹声音,扬尘效果

Prefabs中有粒子效果:DustTrail。

第一、将子弹shell拉到Sence中,给一个rigidBody,设置为Box。把DustTrail也拉进来,并调整DustTrial到炮弹的尾部。

第二、保存合体(异形体)到Prefab中。OK


加发射声音,在tank中添加component: audio source,拖动声音到audio clip

代码如下:

using UnityEngine;using System.Collections;public class tankweapon : MonoBehaviour {public GameObject shell;//炮弹的实体public float shootPower;public Transform shootPoint;//炮弹的起始发射位置private AudioSource audioSource;void Start(){ //大写SaudioSource = GetComponent<AudioSource> ();}void Update () {  //每帧被调用if(Input.GetKeyDown(KeyCode.Space)){//fireshoot();}}void shoot(){GameObject newShell = Instantiate(shell, shootPoint.position, shootPoint.rotation) as GameObject; //实例化炮弹,as类型转化Rigidbody r = newShell.GetComponent<Rigidbody>();//实物体r.velocity = shootPoint.forward * shootPower;//设置炮弹速度audioSource.Play();}}
设置



5.打中之后炮弹爆炸,并且消失

爆炸的粒子效果:Prefabs中的ShellExplosion。

注意:这个效果是要添加到炮弹shell中的。

在Scripts中新建C#,命名为shell,代码如下:

using UnityEngine;using System.Collections;public class shell : MonoBehaviour {public GameObject explosionEffect;void OnCollisionEnter(){Instantiate (explosionEffect,transform.position,transform.rotation);//实例化一个物体Destroy(gameObject);//删除自身}}
拖动脚本到shell中,OK


6.炮弹爆炸声音

可以在爆炸的粒子效果中添加声音元素

add component,audio resource,audio clip

设置如下:



8.目标墙体

GameObject中的Cube,可以复制,拖动,设置为刚体,质量为1(可以只设置一个,然后复制出来的cube都有这性质)。

放好之后,就可以用大炮轰啦~~~~







0 0
原创粉丝点击