UE5 C++ 发射子弹发射(Projectile)

一.相关蓝图的练习,在我之前的文章中射击子弹案例-CSDN博客

本篇使用C++实现

1.创建C++类 MyBullet,在MyBullet.h中包含相关头文件

cpp 复制代码
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Components/StaticMeshComponent.h"  //模型组件
//#include "Components/CapsuleComponent.h"  //球形碰撞组件的头文件
#include "GameFramework/ProjectileMovementComponent.h"   //射击组件
#include <Components/SphereComponent.h> //球形碰撞组件的头文件
#include "MyBullet.generated.h" 

2.声明属性变量,子弹模型,子弹碰撞体,子弹发射器

cpp 复制代码
public:
	UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "MyComponent")
	UStaticMeshComponent* BulletMesh;   //static 组件
	UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "MyComponent")
	USphereComponent* MySphere;    //碰撞组件
	UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "MyComponent")
	UProjectileMovementComponent* FireGunProjectile; //

3.将组件实例化

cpp 复制代码
BulletMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("BulletComponent")); //实例化StaticMesh组件
//RootComponent = 
FireGunProjectile = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("FireGunProjectileComponent")); //实例化ProjectileMovement组件
MySphere = CreateDefaultSubobject<USphereComponent>(TEXT("SphereCollision")); // 

4.通过寻找静态模型,设置静态模型的实例。设置根组件,设置父子级,只要Projectile在根组件后面就能,让物体跟随,就有发射根组件的效果。

再设置参数,调整效果。发射的初始速度,最大速度,重力等。

cpp 复制代码
MySphere = CreateDefaultSubobject<USphereComponent>(TEXT("SphereCollision")); // 
static ConstructorHelpers::FObjectFinder<UStaticMesh>TmpStaticMesh(TEXT("/Script/Engine.StaticMesh'/Engine/BasicShapes/Sphere.Sphere'")); //静态加载资源 重要
BulletMesh->SetStaticMesh(TmpStaticMesh.Object); //.Object重要

RootComponent = BulletMesh;

//FireGunProjectile->setupattack
MySphere->SetupAttachment(RootComponent);
MySphere->InitSphereRadius(67);
FireGunProjectile->SetUpdatedComponent(RootComponent);//
FireGunProjectile->InitialSpeed = 1200.0f;//初始速度
FireGunProjectile->MaxSpeed = 24000.0f; //最大速度
FireGunProjectile->bRotationFollowsVelocity = false; //旋转跟随重力
FireGunProjectile->bIsHomingProjectile = true;    //跟随组件
FireGunProjectile->ProjectileGravityScale = 0.02; //设置重力

5.生成蓝图类放到场景中,这样就能实现单发的子弹效果

相关推荐
星火撩猿2 天前
常见游戏引擎介绍与对比
unity·ue5·游戏引擎·godot
清流君2 天前
【MySQL】数据库 Navicat 可视化工具与 MySQL 命令行基本操作
数据库·人工智能·笔记·mysql·ue5·数字孪生
Involuter3 天前
UE5 Assimp 自用
ue5
电子云与长程纠缠3 天前
Unreal Niagara制作SubUV贴图翻页动画
学习·ue5·编辑器·贴图·niagara
子燕若水3 天前
“Daz to Unreal”将 G8 角色(包括表情)从 daz3d 导入到 UE5。在 UE5 中,我发现使用某个表情并与闭眼混合后,上眼睑出现了问题
3d·ue5
半天法师3 天前
UE5.2+VarjoXR3,Lumen、GI、Nanite无效的两种解决方案
ue5·xr·vr
ue星空3 天前
UE5摄像机画面没有填充满屏幕有黑边
ue5
李詹4 天前
游戏开发核心技术解析——从引擎架构到攻防体系的完整技能树
架构·ue5·游戏引擎·游戏程序·3dsmax·虚幻
子燕若水4 天前
UE5的 Modify Curve 蓝图节点
ue5
人宅6 天前
UE5有些场景的导航生成失败解决方法
ue5