创建角色和摄像机将以下c#代码附加using UnityEngine;
public class ShootingController : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public float bulletSpeed = 10f;
public float cooldownTime = 0.5f;
private float cooldownTimer = 0f;
void Update()
{
cooldownTimer += Time.deltaTime;
if (Input.GetButtonDown("Fire1") && cooldownTimer >= cooldownTime)
{
Shoot();
}
}
void Shoot()
{
cooldownTimer = 0f;
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody bulletRb = bullet.GetComponent<Rigidbody>();
bulletRb.velocity = firePoint.forward * bulletSpeed;
Destroy(bullet, 2f);
}
}
到游戏角色身上
加上换弹效果开枪音效
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class guncontral : MonoBehaviour
{
//枪口火焰生成位置
public Transform firepoint;
//枪口火焰物体
public GameObject fireper;
//子弹生成位置
public Transform bulletpoint;
//子弹物体
public GameObject bulletper;
//子弹个数
private int bulletCount=10;
// 开火间隔
private float cd = 0.2f;
//实际开火的时间 计时器
private float timer=0;
private AudioSource gunvoice;
public AudioClip clip;
// Start is called before the first frame update
void Start()
{
gunvoice = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
//计算实际开火间隔
timer = timer + Time.deltaTime;
if (Input.GetMouseButton(0)&& bulletCount>0&&timer>cd) {
timer = 0;
//火焰生成
Instantiate(fireper, firepoint.position, firepoint.rotation);
//子弹生成
Instantiate(bulletper, bulletpoint.position, bulletpoint.rotation);
bulletCount--;
gunvoice.PlayOneShot(clip);
}
if (bulletCount == 0) {
//Invoke("Reload", 2.0f);
GetComponent<Animator>().SetTrigger("Reload");
Reload();
}
if (Input.GetKeyDown(KeyCode.R)&& bulletCount!=10) {
GetComponent<Animator>().SetTrigger("Reload");
Reload();
}
}
void Reload() {
bulletCount = 10;
}
}