Unity 简单实现子弹射击 您所在的位置:网站首页 unity销毁自身 Unity 简单实现子弹射击

Unity 简单实现子弹射击

2024-07-13 14:29| 来源: 网络整理| 查看: 265

Unity 简单实现子弹射击

一、具体步骤:

1、  创建预制体:Assets >> Create >> Prefab 并命名,添加碰撞(Box Collider 等)并勾选 Is Trigger、添加钢体(Rigidbody)并取消 Use Gravity(暂时不做重力计算);

2、  预制体添加脚本:在Project下找到新创建的预制体,点击AddComponent,添加移动和销毁脚本;

3、  创建空物体或者Cube等等,并调整位置、旋转、缩放等使其和枪口位置一致并作为枪的子物体(移动过程中确保子弹的初始位置始终在枪口位置)即可;

4、  移动角色挂在射击脚本,拖入预制体(1)和创建的空物体(3);

5、  创建Cube作为NPC,挂在被子弹射中脚本,实现被子弹这种显示血量减少直到挂掉。

说明:所有提到脚本都在附录;

二、脚本解释:

Destroy:

1、  没碰撞,特定时间内自动销毁:

Destroy (gameObject,5); //5秒自动销毁 2、触发销毁(射中,碰撞)

void OnTriggerEnter( Collider GetObj) {     if (GetObj != null)  //检测到子弹碰撞销毁        Destroy (gameObject); }

 

Move:     GetComponent().velocity = transform.up * Speed;

   //子弹移动

 

Instantiate:

Instantiate (Bullet, BulletStart.position, 

BulletStart.rotation);

   //克隆预制体 并赋予位置旋转信息  

 

 

 

附录:脚本

 

射击脚本:

using UnityEngine; using System.Collections; using System; public class Fire : MonoBehaviour {     Ray        ray;     string     getObjName;     RaycastHit hit;     public GameObject Bullet;     public Transform  BulletStart;     void Start () {     }     void Update () {             if (Input.GetMouseButtonDown (0)) {                          ray = Camera.main.ScreenPointToRay(Input.mousePosition);                if(Physics.Raycast(ray, out hit))             {                   getObjName = hit.transform.name;             }        Instantiate (Bullet, BulletStart.position, BulletStart.rotation);         }     } }

 

预制体脚本1:移动

 

using UnityEngine; using System.Collections; public class Done_Move : MonoBehaviour {     public float Speed;     void Start () {         GetComponent().velocity = transform.up * Speed;     } }

 

预制体脚本2:销毁

 

using UnityEngine; using System.Collections; public class Out_Destroy : MonoBehaviour {     void Start () {     }     void Update()     {         Destroy (gameObject,5);     }     void OnTriggerEnter( Collider GetObj)     {         if (GetObj != null)             Destroy (gameObject);     } }

 

NPC被子弹射中脚本

 

using UnityEngine; using System.Collections; public class NPC_Attacked : MonoBehaviour {     private string  healthString;     private int     heathnum;     void Start () {         heathnum     = 100;         healthString = " ";     }     void Update () {     }     void OnTriggerEnter( Collider GetObj)     {         //子弹射中判断         if (GetObj.name == "Capsule(Clone)") {  

// "Capsule(Clone)"为创建的预制体名字加“(Clone)”             numAdjust( heathnum,10);         }

    }     void numAdjust( int health,int numDecrease)     {         if (health > 0) {             heathnum -= numDecrease;             healthString = "当前生命值 : + heathnum.ToString ();         } else {             healthString = "嗨,哥们,你挂了";             Destroy (gameObject,2);         }     }     void OnGUI()     {         GUI.Label (new Rect(600,200,100,20),healthString);     } }

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有