//use c++ write a first personal shoot game display on ureal4
// 头文件
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Components/SphereComponent.h"
#include "MyProjectile.generated.h"
UCLASS(config=Game)
class AMyProjectile : public AActor
{
GENERATED_BODY()
public:
// 构造函数
AMyProjectile();
protected:
// 组件
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Projectile)
USphereComponent* CollisionComponent;
// 弹道速度
UPROPERTY(EditDefaultsOnly, Category = Projectile)
float ProjectileSpeed;
// 击中事件
UFUNCTION()
void OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, FVector NormalImpulse, const FHitResult& Hit);
// 更新状态
virtual void Tick(float DeltaTime) override;
// 开始时
virtual void BeginPlay() override;
};
// CPP文件
#include "MyProjectile.h"
#include "GameFramework/ProjectileMovementComponent.h"
// 构造函数
AMyProjectile::AMyProjectile()
{
// 启用物理模拟
CollisionComponent = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComponent"));
CollisionComponent->InitSphereRadius(15.0f);
CollisionComponent->BodyInstance.SetCollisionProfileName("Projectile");
CollisionComponent->OnComponentHit.AddDynamic(this, &AMyProjectile::OnHit);
RootComponent = CollisionComponent;
// 设置弹道速度
ProjectileSpeed = 3000.f;
// 创建弹道移动组件
UProjectileMovementComponent* ProjectileMovementComponent = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("ProjectileMovementComponent"));
ProjectileMovementComponent->SetUpdatedComponent(CollisionComponent);
ProjectileMovementComponent->InitialSpeed = ProjectileSpeed;
ProjectileMovementComponent->MaxSpeed = ProjectileSpeed;
ProjectileMovementComponent->bRotationFollowsVelocity = true;
ProjectileMovementComponent->bShouldBounce = true;
ProjectileMovementComponent->Bounciness = 0.3f;
// 设置初始状态
InitialLifeSpan = 3.0f;
}
// 击中事件
void AMyProjectile::OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, FVector NormalImpulse, const FHitResult& Hit)
{
// 在此处理击中事件
Destroy();
}
// 更新状态
void AMyProjectile::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
// 开始时
void AMyProjectile::BeginPlay()
{
Super::BeginPlay();
}
AI回忆录
于 2023-06-02 22:29:21 首次发布
该文章展示了如何在UnrealEngine4中编写一个基本的射击游戏项目。它涉及到了Actor类的子类AMyProjectile,使用SphereComponent作为碰撞检测,定义了ProjectileSpeed和OnHit事件处理函数,以及设置了ProjectileMovementComponent来控制弹丸的运动。
摘要由CSDN通过智能技术生成