一.相關藍圖的練習,在我之前的文章中射擊子彈案例-CSDN博客
本篇使用C++實現
1.創建C++類 MyBullet,在MyBullet.h中包含相關頭文件
#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.聲明屬性變量,子彈模型,子彈碰撞體,子彈發射器
public:UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "MyComponent")UStaticMeshComponent* BulletMesh; //static 組件UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "MyComponent")USphereComponent* MySphere; //碰撞組件UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "MyComponent")UProjectileMovementComponent* FireGunProjectile; //
3.將組件實例化
BulletMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("BulletComponent")); //實例化StaticMesh組件
//RootComponent =
FireGunProjectile = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("FireGunProjectileComponent")); //實例化ProjectileMovement組件
MySphere = CreateDefaultSubobject<USphereComponent>(TEXT("SphereCollision")); //
4.通過尋找靜態模型,設置靜態模型的實例。設置根組件,設置父子級,只要Projectile在根組件后面就能,讓物體跟隨,就有發射根組件的效果。
再設置參數,調整效果。發射的初始速度,最大速度,重力等。
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.生成藍圖類放到場景中,這樣就能實現單發的子彈效果