两种弹药实例化与发射弹药周期时间

本文提供了两个Unity C#脚本示例,用于实现游戏中的火力控制系统。通过预制体实例化来发射子弹或炮弹,利用Input.GetMouseButtonDown及Input.GetKeyDown检测用户输入,结合Time.time进行时间间隔控制,实现了按鼠标或键盘指定键发射的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实例一:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FireCtrl : MonoBehaviour 
{
    //预制体
    public GameObject bullet;
    //子弹发射位置
    public Transform firePos;

    //发射周期
    private float fireRate = 5.0f;//等待5秒后发射
    private float nextFire = 0.0f;//一开始发射时间
	void Start () 
	{
		
	}
	
	
	void Update () 
	{
        if (Input.GetMouseButtonDown(0) && Time.time >nextFire)
        {
            nextFire = Time.time + fireRate;
            Instantiate(bullet,firePos.position,firePos.rotation);
        }
	}
}




实例二:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FireCannon : MonoBehaviour 
{
    //炮弹预设
    public GameObject cannon = null;

    //炮弹发射初始点
    public Transform firePos;

    //发射周期
    private float fireRate = 5.0f;//等待5秒后发射
    private float nextFire = 0.0f;//一开始发射时间

	void Start () 
	{
        //在Resources文件夹载入弹药预制体
        cannon =(GameObject)Resources.Load("Cannon");
	}
	
	
	void Update () 
	{
        //按键盘 Speed 发射弹药  &&  下一次发射弹药时间
        if (Input.GetKeyDown(KeyCode.Space) && Time.time > nextFire)
        {
            nextFire = Time.time + fireRate;
            Fire();
        }
	}
    void Fire()
    { 
        //生成弹药
        Instantiate(cannon,firePos.position,firePos.rotation);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值