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.生成蓝图类放到场景中,这样就能实现单发的子弹效果

相关推荐
朗迹 - 张伟7 小时前
UE5 UMG学习笔记
笔记·学习·ue5
平行云7 小时前
数字孪生信创云渲染系列(一):混合信创与全国产化架构
unity·ue5·3dsmax·webgl·gpu算力·实时云渲染·像素流送
吴梓穆1 天前
UE5手动放置的树有碰撞,地形刷出来的没有
ue5
Zhichao_971 天前
【UE UMG 材质】虚线框
ue5·材质
朗迹 - 张伟2 天前
UE5.7 基础入门学习笔记
笔记·学习·ue5
朗迹 - 张伟3 天前
UE5 Road Creator Pro 插件学习笔记
笔记·学习·ue5
avi91116 天前
UnReal-UE5虚幻蓝图如何修改
ue5·游戏引擎·虚幻·虚幻引擎·ue·蓝图·蓝图逻辑
郝学胜-神的一滴7 天前
系统设计与面向对象设计:两大设计思想的深度剖析
java·前端·c++·ue5·软件工程
Bluesonli7 天前
UE5 Niagara 系列(02):火焰(噪声 + 颜色曲线 + 透明淡出)——从喷泉思路升级到可用火焰
ue5
a1117768 天前
Elven Girl Belle - UE4/UE5 角色资源(附下载链接)
ue5·ue4