最近在做策划给的一些关于FPS类型的需求,Demo基本已经成型,接下来整理并记录,高手略过,不喜勿喷!!!
废话不多说,直接上代码
public float fireTime; //开火时间
public float coolTime=0.01f; //开火冷却时间
void Update() {
if (fireTime < coolTime) {
fireTime += Time.deltaTime * 3;
//当fireTime小于coolTime 的时候 firetime开始增加到fireTime
}
if (fireTime > coolTime) {
fireTime = coolTime;
}
if (IsFire) {
Ray ray = Camera.main.ScreenPointToRay(screenPos);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) {
if (hit.collider != null && hit.collider.tag != "Player" && fireTime == coolTime) {
//当前第一人称
if (weaponCamera.gameObject.activeInHierarchy) {
fristWeapons[weaponIndex].GetComponent<FPS_Weapon>().Shoot(hit);
} else {
threeWeapons[weaponIndex].GetComponent<FPS_Weapon>().Shoot(hit);
}
}
}
射击代码涉及到第一人称和第三人称切换以及武器的切换,对象池,特效播放,音效播放等在后面会持续更新
public void Shoot(RaycastHit hit) {
//枪口特效
ShootFXFLash.SetActive(true);
ShootFXFLash.GetComponent<ParticleSystem>().Play();
//子弹生成(直接动态生成)
//GameObject bullet = Instantiate(BulletPrefab, ShootBulletPos.position, Quaternion.identity) as GameObject;
//子弹生成(提前生成一批)
//GameObject bullet = bulletsPool[bulletIndex];
//对象池
GameObject bullet = FPS_ObjectPool.GetInstance().GetObj("GenericBulletRayOnly");//子弹名称
bullet.SetActive(false);
bullet.GetComponent<FPS_Bullet>().timeToLive = 2;
bullet.transform.position = ShootBulletPos.position;
bullet.transform.rotation = ShootBulletPos.rotation;
bullet.transform.LookAt(hit.point);
bullet.GetComponent<Rigidbody>().velocity = (hit.point - ShootBulletPos.position) * 10f;
bullet.SetActive(true);
//音效播放
PlayShootAudio();
}
shoot方法里有直接生成子弹,提前生成一批子弹和对象池获取子弹三种生成子弹的测试方式,
射击方法2
只有射击轨道,没有实弹,利用射线碰撞的敌人,设置弹道轨道痕迹,获取敌人身上的伤害脚本赋值伤害
void Shoot() {
particleSystem.Play();
this.lineRenderer.enabled = true;
lineRenderer.SetPosition(0, transform.position);
//判断射击到敌人时的游戏逻辑
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo)) {
lineRenderer.SetPosition(1, hitInfo.point);
//判断当前的射击有没有碰撞到敌人
if (hitInfo.collider.tag == Tags.enemy) {
hitInfo.collider.GetComponent<EnemyHealth>().TakeDamage(attack,hitInfo.point);
}
} else {
lineRenderer.SetPosition(1, transform.position + transform.forward * 100);
}
audio.Play();
Invoke("ClearEffect", 0.05f);
}