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

相关文章

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++

C/C++错误信息处理的常见方法及函数

《C/C++错误信息处理的常见方法及函数》C/C++是两种广泛使用的编程语言,特别是在系统编程、嵌入式开发以及高性能计算领域,:本文主要介绍C/C++错误信息处理的常见方法及函数,文中通过代码介绍... 目录前言1. errno 和 perror()示例:2. strerror()示例:3. perror(

C++变换迭代器使用方法小结

《C++变换迭代器使用方法小结》本文主要介绍了C++变换迭代器使用方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、源码2、代码解析代码解析:transform_iterator1. transform_iterat

详解C++中类的大小决定因数

《详解C++中类的大小决定因数》类的大小受多个因素影响,主要包括成员变量、对齐方式、继承关系、虚函数表等,下面就来介绍一下,具有一定的参考价值,感兴趣的可以了解一下... 目录1. 非静态数据成员示例:2. 数据对齐(Padding)示例:3. 虚函数(vtable 指针)示例:4. 继承普通继承虚继承5.

C++中std::distance使用方法示例

《C++中std::distance使用方法示例》std::distance是C++标准库中的一个函数,用于计算两个迭代器之间的距离,本文主要介绍了C++中std::distance使用方法示例,具... 目录语法使用方式解释示例输出:其他说明:总结std::distance&n编程bsp;是 C++ 标准

C++ 中的 if-constexpr语法和作用

《C++中的if-constexpr语法和作用》if-constexpr语法是C++17引入的新语法特性,也被称为常量if表达式或静态if(staticif),:本文主要介绍C++中的if-c... 目录1 if-constexpr 语法1.1 基本语法1.2 扩展说明1.2.1 条件表达式1.2.2 fa

C++中::SHCreateDirectoryEx函数使用方法

《C++中::SHCreateDirectoryEx函数使用方法》::SHCreateDirectoryEx用于创建多级目录,类似于mkdir-p命令,本文主要介绍了C++中::SHCreateDir... 目录1. 函数原型与依赖项2. 基本使用示例示例 1:创建单层目录示例 2:创建多级目录3. 关键注

C++从序列容器中删除元素的四种方法

《C++从序列容器中删除元素的四种方法》删除元素的方法在序列容器和关联容器之间是非常不同的,在序列容器中,vector和string是最常用的,但这里也会介绍deque和list以供全面了解,尽管在一... 目录一、简介二、移除给定位置的元素三、移除与某个值相等的元素3.1、序列容器vector、deque

C++常见容器获取头元素的方法大全

《C++常见容器获取头元素的方法大全》在C++编程中,容器是存储和管理数据集合的重要工具,不同的容器提供了不同的接口来访问和操作其中的元素,获取容器的头元素(即第一个元素)是常见的操作之一,本文将详细... 目录一、std::vector二、std::list三、std::deque四、std::forwa

C++字符串提取和分割的多种方法

《C++字符串提取和分割的多种方法》在C++编程中,字符串处理是一个常见的任务,尤其是在需要从字符串中提取特定数据时,本文将详细探讨如何使用C++标准库中的工具来提取和分割字符串,并分析不同方法的适用... 目录1. 字符串提取的基本方法1.1 使用 std::istringstream 和 >> 操作符示