UEC++ 虚幻5第三人称射击游戏(一)

2024-06-23 16:52

本文主要是介绍UEC++ 虚幻5第三人称射击游戏(一),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

UEC++ 虚幻5第三人称射击游戏(一)

  • 创建一个空白的C++工程

人物角色基本移动

  • 创建一个Character类
  • 添加一些虚幻商城中的基础动画
    在这里插入图片描述
  • 给角色类添加Camera与SPringArm组件
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "SpringArm")class USpringArmComponent* SpringArm;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Camera")class UCameraComponent* Camera;// Sets default values
AMyCharacter::AMyCharacter()
{// Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArm"));SpringArm->SetupAttachment(GetRootComponent());SpringArm->TargetArmLength = 400.f;SpringArm->bUsePawnControlRotation = true;Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));Camera->SetupAttachment(SpringArm);Camera->bUsePawnControlRotation = false;
}

角色基本移动增强输入系统MyCharacter.h

  • 角色基本移动增强输入系统
// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "InputActionValue.h"
#include "MyCharacter.generated.h"UCLASS()
class SHOOTGAME_API AMyCharacter : public ACharacter
{GENERATED_BODY()public:// Sets default values for this character's propertiesAMyCharacter();UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Input")class UInputMappingContext* DefaultMappingContext;UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Input")class UInputAction* MoveAction;UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Input")class UInputAction* LookAction;UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Input")class UInputAction* CrouchAction;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "SpringArm")class USpringArmComponent* SpringArm;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Camera")class UCameraComponent* Camera;protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;void CharacterMove(const FInputActionValue& Value);void CharacterLook(const FInputActionValue& Value);void BeginCrouch();void EndCtouch();public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;};

角色基本移动增强输入系统MyCharacter.cpp

  • GetMovementComponent()->GetNavAgentPropertiesRef().bCanCrouch = true;:允许角色进行蹲伏(crouch)动作,并且能够影响导航代理(Navigation Agent)的行为
    • GetMovementComponent():获取角色的移动组件
    • GetNavAgentPropertiesRef():获取导航代理属性的引用。这些属性用于定义角色如何与导航系统交互,例如高度、半径、最大爬坡角度等。
    • .bCanCrouch = true;:设置导航代理的一个布尔属性,表示该角色可以进行蹲伏,并且在寻路过程中应当考虑其能通过更低矮的空间。这意味着在自动寻路时,引擎会考虑到角色在蹲伏状态下可以通过的高度限制区域。
  • Crouch与OnCrouch:虚幻自带的蹲伏函数
// Fill out your copyright notice in the Description page of Project Settings.#include "MyCharacter.h"
#include "Camera/CameraComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "EnhancedInputComponent.h"
#include "EnhancedInputSubsystems.h"
#include "GameFramework/PawnMovementComponent.h"
#include "GameFramework/CharacterMovementComponent.h"// Sets default values
AMyCharacter::AMyCharacter()
{// Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;//允许角色进行蹲伏(crouch)动作,并且能够影响导航代理(Navigation Agent)的行为GetMovementComponent()->GetNavAgentPropertiesRef().bCanCrouch = true;//自动转向GetCharacterMovement()->bOrientRotationToMovement = true;//对Character的Pawn的朝向进行硬编码bUseControllerRotationPitch = false;bUseControllerRotationYaw = false;bUseControllerRotationRoll = false;SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArm"));SpringArm->SetupAttachment(GetRootComponent());SpringArm->TargetArmLength = 400.f;SpringArm->bUsePawnControlRotation = true;Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));Camera->SetupAttachment(SpringArm);Camera->bUsePawnControlRotation = false;
}// Called when the game starts or when spawned
void AMyCharacter::BeginPlay()
{Super::BeginPlay();APlayerController* PlayerController = Cast<APlayerController>(Controller);if (PlayerController){UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PlayerController->GetLocalPlayer());if (Subsystem){Subsystem->AddMappingContext(DefaultMappingContext, 0);}}
}void AMyCharacter::CharacterMove(const FInputActionValue& Value)
{FVector2D MovementVector = Value.Get<FVector2D>();if (Controller){FRotator Rotation = Controller->GetControlRotation();FRotator YawRotation = FRotator(0., Rotation.Yaw, 0.);FVector ForwardDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);FVector RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);AddMovementInput(ForwardDirection, MovementVector.Y);AddMovementInput(RightDirection, MovementVector.X);}
}void AMyCharacter::CharacterLook(const FInputActionValue& Value)
{FVector2D LookVector = Value.Get<FVector2D>();if (Controller){AddControllerPitchInput(LookVector.Y);AddControllerYawInput(LookVector.X);}
}void AMyCharacter::BeginCrouch()
{Crouch();
}void AMyCharacter::EndCtouch()
{UnCrouch();
}// Called every frame
void AMyCharacter::Tick(float DeltaTime)
{Super::Tick(DeltaTime);}// Called to bind functionality to input
void AMyCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{Super::SetupPlayerInputComponent(PlayerInputComponent);UEnhancedInputComponent* EnhancedInputComponent = Cast<UEnhancedInputComponent>(PlayerInputComponent);if (EnhancedInputComponent){EnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered, this, &AMyCharacter::CharacterMove);EnhancedInputComponent->BindAction(LookAction, ETriggerEvent::Triggered, this, &AMyCharacter::CharacterLook);EnhancedInputComponent->BindAction(CrouchAction, ETriggerEvent::Triggered, this, &AMyCharacter::BeginCrouch);EnhancedInputComponent->BindAction(CrouchAction, ETriggerEvent::Completed, this, &AMyCharacter::EndCtouch);}}

创建动画蓝图与混合空间

  • 创建一个混合空间1D
    在这里插入图片描述
  • 创建一个动画蓝图,将这个混合空间链接上去
    在这里插入图片描述
    在这里插入图片描述

引入第三人称射击模型

  • 我们新建一个Character蓝图作为第三人称射击测试角色
  • 在虚幻商城里面添加我们需要的射击动画
    在这里插入图片描述
  • 打开这个内容包的动画蓝图
    在这里插入图片描述
  • 我们只需要移动所以跳跃那些都可以删除
    在这里插入图片描述
  • 然后使用这个包自己的动画蓝图与骨骼资产,它的移动全是在动画蓝图中实现的,所以角色蓝图就不用实现移动,用我们创建的角色去使用这个动画蓝图与骨骼资产,然后设置蹲伏的逻辑
    在这里插入图片描述
    在这里插入图片描述

人物动画IK绑定

  • 首先在虚幻商城下载一个自己喜欢的模型添加到项目资产里面
    在这里插入图片描述
  • 添加IK绑定
    在这里插入图片描述
  • 选择我们第三人称射击动作那个骨骼,Pelvis设置为根组件
    在这里插入图片描述
  • 然后添加骨骼链条
    在这里插入图片描述

人物动画重定向

  • 设置自己角色的IK绑定
    在这里插入图片描述
  • 创建重定向器,源是小白人
    在这里插入图片描述
    在这里插入图片描述
  • 导出重定向的动画
    在这里插入图片描述
  • 将动画蓝图给到角色蓝图
    在这里插入图片描述

创建武器类

  • 导入武器模型
  • 创建武器类
    在这里插入图片描述
    在这里插入图片描述
  • 创建武器类的蓝图添加模型上去
    在这里插入图片描述
  • 在角色蓝图中添加一个手持武器的插槽
    在这里插入图片描述
  • 在角色蓝图中,将武器附加到角色手上
    在这里插入图片描述
  • 调整好武器的位置参数
    在这里插入图片描述
  • 运行结果
    在这里插入图片描述

创建武器追踪线

  • Weapon类中创建一个开火的函数,描绘一些射击的追踪线
    在这里插入图片描述
    在这里插入图片描述

  • LineTraceSingleByChannel:使用特定的通道追踪光线并返回第一个阻塞命中TRUE(如果发现了阻塞命中)
    在这里插入图片描述

  • 逻辑源码

void AWeapon::Fire()
{AActor* MyOwner = GetOwner();if (MyOwner){FVector EyeLocation;FRotator EyeRotation;//返回角色视角MyOwner->GetActorEyesViewPoint(EyeLocation, EyeRotation);FVector TraceEnd = EyeLocation + (EyeRotation.Vector() * 10000);FCollisionQueryParams QueryParams;QueryParams.AddIgnoredActor(MyOwner);QueryParams.AddIgnoredActor(this);QueryParams.bTraceComplex = true;FHitResult Hit;//使用特定的通道追踪光线并返回第一个阻塞命中TRUE(如果发现了阻塞命中)if (GetWorld()->LineTraceSingleByChannel(Hit, EyeLocation, TraceEnd, ECC_Visibility, QueryParams)){//设置受阻,造成伤害结果}DrawDebugLine(GetWorld(), EyeLocation, TraceEnd,FColor::Red,false,1.0f,0,1.0f);}
}

调整追踪线位置

  • 我们需要将追踪线变为我们摄像机眼睛看见的位置,我们需要重写APawn类中的GetPawnViewLocation函数
    在这里插入图片描述
    在这里插入图片描述
  • 在角色蓝图中实例化对象Weapon类,进行鼠标左键点击测试绘画的线是否是从摄像机眼睛处发出
    在这里插入图片描述
  • 运行结果
    请添加图片描述

创建伤害效果

  • 补全Fire函数中的伤害处理逻辑
  • 首先添加一个UDamageType模版变量,来存储造成伤害的类
    在这里插入图片描述
  • 补全逻辑
    在这里插入图片描述
  • Fire函数
void AWeapon::Fire()
{AActor* MyOwner = GetOwner();if (MyOwner){FVector EyeLocation;FRotator EyeRotation;//返回角色视角MyOwner->GetActorEyesViewPoint(EyeLocation, EyeRotation);FVector TraceEnd = EyeLocation + (EyeRotation.Vector() * 10000);FCollisionQueryParams QueryParams;QueryParams.AddIgnoredActor(MyOwner);QueryParams.AddIgnoredActor(this);QueryParams.bTraceComplex = true;FHitResult Hit;FVector ShotDirection = EyeRotation.Vector();//使用特定的通道追踪光线并返回第一个阻塞命中TRUE(如果发现了阻塞命中)if (GetWorld()->LineTraceSingleByChannel(Hit, EyeLocation, TraceEnd, ECC_Visibility, QueryParams)){//设置受阻,造成伤害结果AActor* HitActor = Hit.GetActor();UGameplayStatics::ApplyPointDamage(HitActor, 10.f, ShotDirection, Hit, MyOwner->GetInstigatorController(),this, DamageType);}DrawDebugLine(GetWorld(), EyeLocation, TraceEnd,FColor::Red,false,1.0f,0,1.0f);}
}
  • 运行结果

创建射击特效

  • 导入粒子资源
  • 添加两个粒子系统,与一个附加到骨骼的变量
    在这里插入图片描述
  • 默认骨骼名
    在这里插入图片描述
  • Fire函数中添加特效与位置逻辑,一个是开火的特效粒子,一个是子弹打击到目标身上的掉血粒子
    在这里插入图片描述
  • 将特效添加到武器蓝图中
    在这里插入图片描述
  • 将武器骨骼插槽的名字改为我们设置的名字
    在这里插入图片描述
  • 微调一下摄像机方便测试
    在这里插入图片描述
  • 运行结果
    请添加图片描述

Weapon.h

// Fill out your copyright notice in the Description page of Project Settings.
#pragma once#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Weapon.generated.h"UCLASS()
class SHOOTGAME_API AWeapon : public AActor
{GENERATED_BODY()public:	// Sets default values for this actor's propertiesAWeapon();protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;//武器骨骼UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "Components")class USkeletalMeshComponent* SkeletalComponent;//开火UFUNCTION(BlueprintCallable,Category = "WeaponFire")void Fire();//描述所造成的伤害的类UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Weapon")TSubclassOf<class UDamageType> DamageType;//炮口粒子系统UPROPERTY(EditAnywhere,BlueprintReadOnly,Category="WeaponParticle")class UParticleSystem* MuzzleEffect;//粒子附加到骨骼的名字UPROPERTY(EditAnywhere,BlueprintReadOnly,Category="WeaponParticle")FName MuzzleSocketName;//撞击到敌人身上的粒子系统UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "WeaponParticle")UParticleSystem* ImpactEffect;
public:	// Called every framevirtual void Tick(float DeltaTime) override;};

Weapon.cpp

// Fill out your copyright notice in the Description page of Project Settings.
#include "Weapon.h"
#include <Kismet/GameplayStatics.h>
#include "Particles/ParticleSystem.h"
// Sets default values
AWeapon::AWeapon()
{// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;SkeletalComponent = CreateAbstractDefaultSubobject<USkeletalMeshComponent>(TEXT("SkeletalComponent"));SkeletalComponent->SetupAttachment(GetRootComponent());MuzzleSocketName = "MuzzleSocket";
}// Called when the game starts or when spawned
void AWeapon::BeginPlay()
{Super::BeginPlay();}void AWeapon::Fire()
{AActor* MyOwner = GetOwner();if (MyOwner){FVector EyeLocation;FRotator EyeRotation;//返回角色视角MyOwner->GetActorEyesViewPoint(EyeLocation, EyeRotation);FVector TraceEnd = EyeLocation + (EyeRotation.Vector() * 10000);FCollisionQueryParams QueryParams;QueryParams.AddIgnoredActor(MyOwner);QueryParams.AddIgnoredActor(this);QueryParams.bTraceComplex = true;FHitResult Hit;FVector ShotDirection = EyeRotation.Vector();//使用特定的通道追踪光线并返回第一个阻塞命中TRUE(如果发现了阻塞命中)if (GetWorld()->LineTraceSingleByChannel(Hit, EyeLocation, TraceEnd, ECC_Visibility, QueryParams)){//设置受阻,造成伤害结果AActor* HitActor = Hit.GetActor();UGameplayStatics::ApplyPointDamage(HitActor, 10.f, ShotDirection, Hit, MyOwner->GetInstigatorController(),this, DamageType);//粒子生成的位置UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ImpactEffect, Hit.ImpactPoint,Hit.ImpactNormal.Rotation());}DrawDebugLine(GetWorld(), EyeLocation, TraceEnd,FColor::Red,false,1.0f,0,1.0f);if (MuzzleEffect){//附加粒子效果UGameplayStatics::SpawnEmitterAttached(MuzzleEffect,SkeletalComponent,MuzzleSocketName);}}
}// Called every frame
void AWeapon::Tick(float DeltaTime)
{Super::Tick(DeltaTime);}

创建十字准心

  • 创建一个控件蓝图作为十字准心的窗口
    在这里插入图片描述
  • 在角色蓝图的BeginPlay中添加这个视口到窗口中
    在这里插入图片描述
  • 运行结果
    在这里插入图片描述

MyCharacter.h

// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "InputActionValue.h"
#include "MyCharacter.generated.h"UCLASS()
class SHOOTGAME_API AMyCharacter : public ACharacter
{GENERATED_BODY()public:// Sets default values for this character's propertiesAMyCharacter();UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Input")class UInputMappingContext* DefaultMappingContext;UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Input")class UInputAction* MoveAction;UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Input")class UInputAction* LookAction;UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Input")class UInputAction* CrouchAction;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "SpringArm")class USpringArmComponent* SpringArm;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Camera")class UCameraComponent* Camera;//UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Animation", meta = (AllowPrivateAccess = "true"))//class UAnimInstance* MyAnimInstance; // 或者使用 TSubclassOf<UAnimInstance> 作为类型指向动画蓝图类protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;void CharacterMove(const FInputActionValue& Value);void CharacterLook(const FInputActionValue& Value);void BeginCrouch();void EndCtouch();public:	// Called every framevirtual void Tick(float DeltaTime) override;// Called to bind functionality to inputvirtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;//重写GetPawnViewLocation函数将其返回摄像机的眼睛看见的位置virtual FVector GetPawnViewLocation() const override;
};

MyCharacter.cpp

// Fill out your copyright notice in the Description page of Project Settings.#include "MyCharacter.h"
#include "Camera/CameraComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "EnhancedInputComponent.h"
#include "EnhancedInputSubsystems.h"
#include "GameFramework/PawnMovementComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "Engine/Engine.h"// Sets default values
AMyCharacter::AMyCharacter()
{// Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;//允许角色进行蹲伏(crouch)动作,并且能够影响导航代理(Navigation Agent)的行为GetMovementComponent()->GetNavAgentPropertiesRef().bCanCrouch = true;//自动转向GetCharacterMovement()->bOrientRotationToMovement = true;//对Character的Pawn的朝向进行硬编码bUseControllerRotationPitch = false;bUseControllerRotationYaw = false;bUseControllerRotationRoll = false;SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArm"));SpringArm->SetupAttachment(GetRootComponent());SpringArm->TargetArmLength = 400.f;SpringArm->bUsePawnControlRotation = true;Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));Camera->SetupAttachment(SpringArm);Camera->bUsePawnControlRotation = false;
}// Called when the game starts or when spawned
void AMyCharacter::BeginPlay()
{Super::BeginPlay();APlayerController* PlayerController = Cast<APlayerController>(Controller);if (PlayerController){UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PlayerController->GetLocalPlayer());if (Subsystem){Subsystem->AddMappingContext(DefaultMappingContext, 0);}}
}void AMyCharacter::CharacterMove(const FInputActionValue& Value)
{FVector2D MovementVector = Value.Get<FVector2D>();if (Controller){FRotator Rotation = Controller->GetControlRotation();FRotator YawRotation = FRotator(0., Rotation.Yaw, 0.);FVector ForwardDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);FVector RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);AddMovementInput(ForwardDirection, MovementVector.Y);AddMovementInput(RightDirection, MovementVector.X);}
}void AMyCharacter::CharacterLook(const FInputActionValue& Value)
{FVector2D LookVector = Value.Get<FVector2D>();if (Controller){AddControllerPitchInput(LookVector.Y);AddControllerYawInput(LookVector.X);}
}void AMyCharacter::BeginCrouch()
{//bIsCrouched = true;//Crouch();//FString MessageString;//MessageString.AppendInt((TEXT("bIsCrouched is111, %s"), bIsCrouched));//GEngine->AddOnScreenDebugMessage(0, 10.f, FColor::Red, MessageString);GEngine->AddOnScreenDebugMessage(0, 10.f, FColor::Red, FString::Printf(bIsCrouched));
}void AMyCharacter::EndCtouch()
{//bIsCrouched = false;//UnCrouch();//FString MessageString;//MessageString.AppendInt((TEXT("bIsCrouched is222, %s"), bIsCrouched));//GEngine->AddOnScreenDebugMessage(0, 10.f, FColor::Red, MessageString);
}// Called every frame
void AMyCharacter::Tick(float DeltaTime)
{Super::Tick(DeltaTime);}// Called to bind functionality to input
void AMyCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{Super::SetupPlayerInputComponent(PlayerInputComponent);UEnhancedInputComponent* EnhancedInputComponent = Cast<UEnhancedInputComponent>(PlayerInputComponent);if (EnhancedInputComponent){EnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered, this, &AMyCharacter::CharacterMove);EnhancedInputComponent->BindAction(LookAction, ETriggerEvent::Triggered, this, &AMyCharacter::CharacterLook);EnhancedInputComponent->BindAction(CrouchAction, ETriggerEvent::Triggered, this, &AMyCharacter::BeginCrouch);EnhancedInputComponent->BindAction(CrouchAction, ETriggerEvent::Completed, this, &AMyCharacter::EndCtouch);}}FVector AMyCharacter::GetPawnViewLocation() const
{if (Camera){//返回摄像机眼睛的位置return Camera->GetComponentLocation();}return Super::GetPawnViewLocation();
}

Weapon.h

// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Weapon.generated.h"UCLASS()
class SHOOTGAME_API AWeapon : public AActor
{GENERATED_BODY()public:	// Sets default values for this actor's propertiesAWeapon();protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;//武器骨骼UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "Components")class USkeletalMeshComponent* SkeletalComponent;//开火UFUNCTION(BlueprintCallable,Category = "WeaponFire")void Fire();//描述所造成的伤害的类UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Weapon")TSubclassOf<class UDamageType> DamageType;//炮口粒子系统UPROPERTY(EditAnywhere,BlueprintReadOnly,Category="WeaponParticle")class UParticleSystem* MuzzleEffect;//粒子附加到骨骼的名字UPROPERTY(EditAnywhere,BlueprintReadOnly,Category="WeaponParticle")FName MuzzleSocketName;//撞击到敌人身上的粒子系统UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "WeaponParticle")UParticleSystem* ImpactEffect;
public:	// Called every framevirtual void Tick(float DeltaTime) override;};

Weapon.cpp

// Fill out your copyright notice in the Description page of Project Settings.#include "Weapon.h"
#include <Kismet/GameplayStatics.h>
#include "Particles/ParticleSystem.h"
// Sets default values
AWeapon::AWeapon()
{// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;SkeletalComponent = CreateAbstractDefaultSubobject<USkeletalMeshComponent>(TEXT("SkeletalComponent"));SkeletalComponent->SetupAttachment(GetRootComponent());MuzzleSocketName = "MuzzleSocket";
}// Called when the game starts or when spawned
void AWeapon::BeginPlay()
{Super::BeginPlay();}void AWeapon::Fire()
{AActor* MyOwner = GetOwner();if (MyOwner){FVector EyeLocation;FRotator EyeRotation;//返回角色视角MyOwner->GetActorEyesViewPoint(EyeLocation, EyeRotation);FVector TraceEnd = EyeLocation + (EyeRotation.Vector() * 10000);FCollisionQueryParams QueryParams;QueryParams.AddIgnoredActor(MyOwner);QueryParams.AddIgnoredActor(this);QueryParams.bTraceComplex = true;FHitResult Hit;FVector ShotDirection = EyeRotation.Vector();//使用特定的通道追踪光线并返回第一个阻塞命中TRUE(如果发现了阻塞命中)if (GetWorld()->LineTraceSingleByChannel(Hit, EyeLocation, TraceEnd, ECC_Visibility, QueryParams)){//设置受阻,造成伤害结果AActor* HitActor = Hit.GetActor();UGameplayStatics::ApplyPointDamage(HitActor, 10.f, ShotDirection, Hit, MyOwner->GetInstigatorController(),this, DamageType);//粒子生成的位置UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ImpactEffect, Hit.ImpactPoint,Hit.ImpactNormal.Rotation());}DrawDebugLine(GetWorld(), EyeLocation, TraceEnd,FColor::White,false,1.0f,0,1.0f);if (MuzzleEffect){//附加粒子效果UGameplayStatics::SpawnEmitterAttached(MuzzleEffect,SkeletalComponent,MuzzleSocketName);}}
}// Called every frame
void AWeapon::Tick(float DeltaTime)
{Super::Tick(DeltaTime);}

这篇关于UEC++ 虚幻5第三人称射击游戏(一)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1087730

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

c++中std::placeholders的使用方法

《c++中std::placeholders的使用方法》std::placeholders是C++标准库中的一个工具,用于在函数对象绑定时创建占位符,本文就来详细的介绍一下,具有一定的参考价值,感兴... 目录1. 基本概念2. 使用场景3. 示例示例 1:部分参数绑定示例 2:参数重排序4. 注意事项5.

使用C++将处理后的信号保存为PNG和TIFF格式

《使用C++将处理后的信号保存为PNG和TIFF格式》在信号处理领域,我们常常需要将处理结果以图像的形式保存下来,方便后续分析和展示,C++提供了多种库来处理图像数据,本文将介绍如何使用stb_ima... 目录1. PNG格式保存使用stb_imagephp_write库1.1 安装和包含库1.2 代码解

C++实现封装的顺序表的操作与实践

《C++实现封装的顺序表的操作与实践》在程序设计中,顺序表是一种常见的线性数据结构,通常用于存储具有固定顺序的元素,与链表不同,顺序表中的元素是连续存储的,因此访问速度较快,但插入和删除操作的效率可能... 目录一、顺序表的基本概念二、顺序表类的设计1. 顺序表类的成员变量2. 构造函数和析构函数三、顺序表

使用C++实现单链表的操作与实践

《使用C++实现单链表的操作与实践》在程序设计中,链表是一种常见的数据结构,特别是在动态数据管理、频繁插入和删除元素的场景中,链表相比于数组,具有更高的灵活性和高效性,尤其是在需要频繁修改数据结构的应... 目录一、单链表的基本概念二、单链表类的设计1. 节点的定义2. 链表的类定义三、单链表的操作实现四、

使用C/C++调用libcurl调试消息的方式

《使用C/C++调用libcurl调试消息的方式》在使用C/C++调用libcurl进行HTTP请求时,有时我们需要查看请求的/应答消息的内容(包括请求头和请求体)以方便调试,libcurl提供了多种... 目录1. libcurl 调试工具简介2. 输出请求消息使用 CURLOPT_VERBOSE使用 C

C++实现获取本机MAC地址与IP地址

《C++实现获取本机MAC地址与IP地址》这篇文章主要为大家详细介绍了C++实现获取本机MAC地址与IP地址的两种方式,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 实际工作中,项目上常常需要获取本机的IP地址和MAC地址,在此使用两种方案获取1.MFC中获取IP和MAC地址获取