本节最终效果
前言
本节就先实现添加武器,一些射击基本功能实现。
绑定人物手臂和武器
这里我找了一个人的手臂和武器动画素材
https://sketchfab.com/3d-models/cz-scorpion-evo3-a1-ultimate-fps-animations-f2bdfac775344004ad38d0318f0664a4
将他拖入到为摄像机的子集,然后调整到合适位置即可
你会发现手臂有一部分没法正常显示,那是因为默认摄像机只会投射大于0.3外的范围,所以我们需要把摄像机投射最小范围尽量改小,这里设置为0.01即可
枪准心
这里就随便画一个UI即可,放在0位置,指示准心,效果如下
射线发射子弹
新增WeaponController
public class WeaponController : MonoBehaviour
{
public Transform shooterPoint; // 射击的位置
public int bulletsMag = 30; // 一个弹匣子弹数量
public int range = 100; // 武器的射程
public int bulletLeft = 300; // 备弹
void Update()
{
if (Input.GetMouseButton(0))
{
GunFire();
}
}
///<summary>
/// 射击
///</summary>
public void GunFire()
{
RaycastHit hit;
Vector3 shootDirection = shooterPoint.forward; // 射击方向(向前)
//场景显示红线,方便调试查看
Debug.DrawRay(shooterPoint.position, shooterPoint.position + shootDirection * range, Color.red);
if (Physics.Raycast(shooterPoint.position, shootDirection, out hit, range)) // 判断射击
{
Debug.Log(hit.transform.name + "被击中了");
}
}
}
挂载脚本,ShootPoint记得一定要放在摄像机0,0,0位置
效果
控制射速
public float fireRate = 0.1f;//射速
private float fireTimer;//计时器
void Update()
{
if (Input.GetMouseButton(0) && currentBullects > 0)
{
GunFire();
}
//定时器
if (fireTimer < fireRate)
{
fireTimer += Time.deltaTime;
}
}
// 射击
public void GunFire()
{
if (fireTimer < fireRate) return;
RaycastHit hit;
Vector3 shootDirection = shooterPoint.forward; // 射击方向(向前)
//场景显示红线,方便调试查看
Debug.DrawRay(shooterPoint.position, shooterPoint.position + shootDirection * range, Color.red);
if (Physics.Raycast(shooterPoint.position, shootDirection, out hit, range)) // 判断射击
{
Debug.Log(hit.transform.name + "被击中了");
}
fireTimer = 0;
}
效果,每过0.1秒射击一次
打空一个弹夹
public int currentBullets; // 当前子弹数量
private void Start()
{
currentBullects = bulletsMag;
}
public void GunFire()
{
if (fireTimer < fireRate || currentBullects <= 0) return;
//。。。
currentBullects--;
}
显示子弹数
绘制简单的UI
public TextMeshProUGUI AmmoTextUI;//子弹UI
void Update()
{
//。。。
UpdateAmmoUI();
}
//更新子弹UI
private void UpdateAmmoUI()
{
AmmoTextUI.text = currentBullects + "/" + bulletLeft;
}
效果
换弹
if (Input.GetKeyDown(KeyCode.R))
{
Reload();
}
//换弹
public void Reload()
{
if (bulletLeft <= 0) return;
//计算需要填装的子弹数=1个弹匣子弹数-当前弹匣子弹数
int bullectToLoad = bulletsMag - currentBullects;
//计算备弹需扣除子弹数
int bullectToReduce = (bulletLeft >= bullectToLoad) ? bullectToLoad : bulletLeft;
bulletLeft -= bullectToReduce;//减少备弹数
currentBullects += bullectToReduce;//当前子弹数增加
}
效果
源码
源码在最后一节
完结
赠人玫瑰,手有余香!如果文章内容对你有所帮助,请不要吝啬你的点赞评论和关注
,以便我第一时间收到反馈,你的每一次支持
都是我不断创作的最大动力。当然如果你发现了文章中存在错误
或者有更好的解决方法
,也欢迎评论私信告诉我哦!
好了,我是向宇
,https://xiangyu.blog.csdn.net文章来源:https://www.toymoban.com/news/detail-846113.html
一位在小公司默默奋斗的开发者,出于兴趣爱好,于是最近才开始自习unity。如果你遇到任何问题,也欢迎你评论私信找我, 虽然有些问题我可能也不一定会,但是我会查阅各方资料,争取给出最好的建议,希望可以帮助更多想学编程的人,共勉~文章来源地址https://www.toymoban.com/news/detail-846113.html
到了这里,关于【用unity实现100个游戏之18】从零开始制作一个类CSGO/CS2、CF第一人称FPS射击游戏——基础篇2(附项目源码)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!