unity坦克发射炮弹,并显示特效

步骤

  1. 给坦克在发射炮口的位置添加一个空物体,用来得到实例化炮弹的位置,z轴为方向。
  2. 在tank的脚本中,得到空物体的位置,并初始化炮弹,再给炮弹一个初始速度,因为添加了rigibody刚体组件,飞行会自己模拟物理飞行轨迹
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TankFire : MonoBehaviour
{
	//炮弹物体,再untiy面板中赋值
    public GameObject firePrefab;
    //keycode,按下发射炮弹,unity面板中赋值
    public KeyCode mKeyCode;
	//炮弹速度,可在unity面板中赋值
    public float shellSpeed = 10;
	//发射的位置,我们放置的空物体
    private Transform _firePosition;
    
    // Start is called before the first frame update
    void Start()
    {	
    	//得到防止的空物体的位置
        _firePosition = transform.Find("FirePosition");
    }

    // Update is called once per frame
    void Update()
    {
    	//如果按下自定义按键
        if (Input.GetKeyDown(mKeyCode))
        {
        	//初始化炮弹实例
            GameObject fireInstance =
                GameObject.Instantiate(firePrefab, _firePosition.position, _firePosition.rotation);
            //发射炮弹,给炮弹的刚体组件一个速度和方向
            fireInstance.GetComponent<Rigidbody>().velocity = fireInstance.transform.forward * shellSpeed;
        }
    }
}

  1. 给炮弹添加一个collider组件,并设置炮弹为is Trigger,触发检测,触发时销毁炮弹,并播放爆炸效果
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class shell : MonoBehaviour
{
	//爆炸效果
    public GameObject boomPrefab;
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

	//触发检测
    void OnTriggerEnter(Collider other)
    {
    	//销毁炮弹本身
        Destroy(this.gameObject);
        //实例化爆炸效果,在触发的位置和方向
        GameObject.Instantiate(boomPrefab, transform.position, transform.rotation);
    }

}

  1. 给特效打上paly on Awake初始化时立即播放,如下图,并在一定时间(播放完毕后消失)
    在这里插入图片描述
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShellExposition : MonoBehaviour
{
	//播放时间
    private float _existTime = 1.5f;


    // Start is called before the first frame update
    void Start()
    {
    	//一初始化,就立即进行定时销毁
        Destroy(this.gameObject,_existTime);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

  • 10
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值