UE4 第一人称游戏和界面操作交互

编程入门 行业动态 更新时间:2024-10-27 07:20:45

UE4 第一<a href=https://www.elefans.com/category/jswz/34/1767335.html style=人称游戏和界面操作交互"/>

UE4 第一人称游戏和界面操作交互

在HUD界面上显示当前发出的子弹数量。如下图所示:

  1. 在角色类中添加一个变量用来保存发射的子弹的数量
//记录子弹的数量UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "AAA")int32 projectileCount = 0;
  1. 在cpp中实现,当开火以后,子弹的数量就会加+1
	projectileCount += 1;
  1. 以下是完整的代码:
// Copyright Epic Games, Inc. All Rights Reserved.#pragma once#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "TrueFPSProjectCharacter.generated.h"class UInputComponent;
class USkeletalMeshComponent;
class USceneComponent;
class UCameraComponent;
class UMotionControllerComponent;
class UAnimMontage;
class USoundBase;UCLASS(config=Game)
class ATrueFPSProjectCharacter : public ACharacter
{GENERATED_BODY()/** Pawn mesh: 1st person view (arms; seen only by self) */UPROPERTY(VisibleDefaultsOnly, Category=Mesh)USkeletalMeshComponent* Mesh1P;/** Gun mesh: 1st person view (seen only by self) */UPROPERTY(VisibleDefaultsOnly, Category = Mesh)USkeletalMeshComponent* FP_Gun;/** Location on gun mesh where projectiles should spawn. */UPROPERTY(VisibleDefaultsOnly, Category = Mesh)USceneComponent* FP_MuzzleLocation;/** Gun mesh: VR view (attached to the VR controller directly, no arm, just the actual gun) */UPROPERTY(VisibleDefaultsOnly, Category = Mesh)USkeletalMeshComponent* VR_Gun;/** Location on VR gun mesh where projectiles should spawn. */UPROPERTY(VisibleDefaultsOnly, Category = Mesh)USceneComponent* VR_MuzzleLocation;/** First person camera */UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))UCameraComponent* FirstPersonCameraComponent;/** Motion controller (right hand) */UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))UMotionControllerComponent* R_MotionController;/** Motion controller (left hand) */UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))UMotionControllerComponent* L_MotionController;public:ATrueFPSProjectCharacter();protected:virtual void BeginPlay();public:/** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)float BaseTurnRate;/** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)float BaseLookUpRate;/** Gun muzzle's offset from the characters location */UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=Gameplay)FVector GunOffset;/** Projectile class to spawn */UPROPERTY(EditDefaultsOnly, Category=Projectile)TSubclassOf<class ATrueFPSProjectProjectile> ProjectileClass;/** Sound to play each time we fire */UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=Gameplay)USoundBase* FireSound;/** AnimMontage to play each time we fire */UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay)UAnimMontage* FireAnimation;/** Whether to use motion controller location for aiming. */UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay)uint8 bUsingMotionControllers : 1;//记录子弹的数量UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "AAA")int32 projectileCount = 0;protected:/** Fires a projectile. */void OnFire();/** Resets HMD orientation and position in VR. */void OnResetVR();/** Handles moving forward/backward */void MoveForward(float Val);/** Handles stafing movement, left and right */void MoveRight(float Val);/*** Called via input to turn at a given rate.* @param Rate	This is a normalized rate, i.e. 1.0 means 100% of desired turn rate*/void TurnAtRate(float Rate);/*** Called via input to turn look up/down at a given rate.* @param Rate	This is a normalized rate, i.e. 1.0 means 100% of desired turn rate*/void LookUpAtRate(float Rate);struct TouchData{TouchData() { bIsPressed = false;Location=FVector::ZeroVector;}bool bIsPressed;ETouchIndex::Type FingerIndex;FVector Location;bool bMoved;};void BeginTouch(const ETouchIndex::Type FingerIndex, const FVector Location);void EndTouch(const ETouchIndex::Type FingerIndex, const FVector Location);void TouchUpdate(const ETouchIndex::Type FingerIndex, const FVector Location);TouchData	TouchItem;protected:// APawn interfacevirtual void SetupPlayerInputComponent(UInputComponent* InputComponent) override;// End of APawn interface/* * Configures input for touchscreen devices if there is a valid touch interface for doing so ** @param	InputComponent	The input component pointer to bind controls to* @returns true if touch controls were enabled.*/bool EnableTouchscreenMovement(UInputComponent* InputComponent);public:/** Returns Mesh1P subobject **/USkeletalMeshComponent* GetMesh1P() const { return Mesh1P; }/** Returns FirstPersonCameraComponent subobject **/UCameraComponent* GetFirstPersonCameraComponent() const { return FirstPersonCameraComponent; }};
// Copyright Epic Games, Inc. All Rights Reserved.#include "TrueFPSProjectCharacter.h"
#include "TrueFPSProjectProjectile.h"
#include "Animation/AnimInstance.h"
#include "Camera/CameraComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/InputSettings.h"
#include "HeadMountedDisplayFunctionLibrary.h"
#include "Kismet/GameplayStatics.h"
#include "MotionControllerComponent.h"
#include "XRMotionControllerBase.h" // for FXRMotionControllerBase::RightHandSourceIdDEFINE_LOG_CATEGORY_STATIC(LogFPChar, Warning, All);//
// ATrueFPSProjectCharacterATrueFPSProjectCharacter::ATrueFPSProjectCharacter()
{// Set size for collision capsuleGetCapsuleComponent()->InitCapsuleSize(55.f, 96.0f);// set our turn rates for inputBaseTurnRate = 45.f;BaseLookUpRate = 45.f;// Create a CameraComponent	FirstPersonCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("FirstPersonCamera"));FirstPersonCameraComponent->SetupAttachment(GetCapsuleComponent());FirstPersonCameraComponent->SetRelativeLocation(FVector(-39.56f, 1.75f, 64.f)); // Position the cameraFirstPersonCameraComponent->bUsePawnControlRotation = true;// Create a mesh component that will be used when being viewed from a '1st person' view (when controlling this pawn)Mesh1P = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("CharacterMesh1P"));Mesh1P->SetOnlyOwnerSee(true);Mesh1P->SetupAttachment(FirstPersonCameraComponent);Mesh1P->bCastDynamicShadow = false;Mesh1P->CastShadow = false;Mesh1P->SetRelativeRotation(FRotator(1.9f, -19.19f, 5.2f));Mesh1P->SetRelativeLocation(FVector(-0.5f, -4.4f, -155.7f));// Create a gun mesh componentFP_Gun = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("FP_Gun"));FP_Gun->SetOnlyOwnerSee(false);			// otherwise won't be visible in the multiplayerFP_Gun->bCastDynamicShadow = false;FP_Gun->CastShadow = false;// FP_Gun->SetupAttachment(Mesh1P, TEXT("GripPoint"));FP_Gun->SetupAttachment(RootComponent);FP_MuzzleLocation = CreateDefaultSubobject<USceneComponent>(TEXT("MuzzleLocation"));FP_MuzzleLocation->SetupAttachment(FP_Gun);FP_MuzzleLocation->SetRelativeLocation(FVector(0.2f, 48.4f, -10.6f));// Default offset from the character location for projectiles to spawnGunOffset = FVector(100.0f, 0.0f, 10.0f);// Note: The ProjectileClass and the skeletal mesh/anim blueprints for Mesh1P, FP_Gun, and VR_Gun // are set in the derived blueprint asset named MyCharacter to avoid direct content references in C++.// Create VR Controllers.R_MotionController = CreateDefaultSubobject<UMotionControllerComponent>(TEXT("R_MotionController"));R_MotionController->MotionSource = FXRMotionControllerBase::RightHandSourceId;R_MotionController->SetupAttachment(RootComponent);L_MotionController = CreateDefaultSubobject<UMotionControllerComponent>(TEXT("L_MotionController"));L_MotionController->SetupAttachment(RootComponent);// Create a gun and attach it to the right-hand VR controller.// Create a gun mesh componentVR_Gun = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("VR_Gun"));VR_Gun->SetOnlyOwnerSee(false);			// otherwise won't be visible in the multiplayerVR_Gun->bCastDynamicShadow = false;VR_Gun->CastShadow = false;VR_Gun->SetupAttachment(R_MotionController);VR_Gun->SetRelativeRotation(FRotator(0.0f, -90.0f, 0.0f));VR_MuzzleLocation = CreateDefaultSubobject<USceneComponent>(TEXT("VR_MuzzleLocation"));VR_MuzzleLocation->SetupAttachment(VR_Gun);VR_MuzzleLocation->SetRelativeLocation(FVector(0.000004, 53.999992, 10.000000));VR_MuzzleLocation->SetRelativeRotation(FRotator(0.0f, 90.0f, 0.0f));		// Counteract the rotation of the VR gun model.// Uncomment the following line to turn motion controllers on by default://bUsingMotionControllers = true;
}void ATrueFPSProjectCharacter::BeginPlay()
{// Call the base class  Super::BeginPlay();//Attach gun mesh component to Skeleton, doing it here because the skeleton is not yet created in the constructorFP_Gun->AttachToComponent(Mesh1P, FAttachmentTransformRules(EAttachmentRule::SnapToTarget, true), TEXT("GripPoint"));// Show or hide the two versions of the gun based on whether or not we're using motion controllers.if (bUsingMotionControllers){VR_Gun->SetHiddenInGame(false, true);Mesh1P->SetHiddenInGame(true, true);}else{VR_Gun->SetHiddenInGame(true, true);Mesh1P->SetHiddenInGame(false, true);}
}//
// Inputvoid ATrueFPSProjectCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{// set up gameplay key bindingscheck(PlayerInputComponent);// Bind jump eventsPlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);// Bind fire eventPlayerInputComponent->BindAction("Fire", IE_Pressed, this, &ATrueFPSProjectCharacter::OnFire);// Enable touchscreen inputEnableTouchscreenMovement(PlayerInputComponent);PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &ATrueFPSProjectCharacter::OnResetVR);// Bind movement eventsPlayerInputComponent->BindAxis("MoveForward", this, &ATrueFPSProjectCharacter::MoveForward);PlayerInputComponent->BindAxis("MoveRight", this, &ATrueFPSProjectCharacter::MoveRight);// We have 2 versions of the rotation bindings to handle different kinds of devices differently// "turn" handles devices that provide an absolute delta, such as a mouse.// "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystickPlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);PlayerInputComponent->BindAxis("TurnRate", this, &ATrueFPSProjectCharacter::TurnAtRate);PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);PlayerInputComponent->BindAxis("LookUpRate", this, &ATrueFPSProjectCharacter::LookUpAtRate);
}void ATrueFPSProjectCharacter::OnFire()
{// try and fire a projectileif (ProjectileClass != nullptr){UWorld* const World = GetWorld();if (World != nullptr){if (bUsingMotionControllers){const FRotator SpawnRotation = VR_MuzzleLocation->GetComponentRotation();const FVector SpawnLocation = VR_MuzzleLocation->GetComponentLocation();World->SpawnActor<ATrueFPSProjectProjectile>(ProjectileClass, SpawnLocation, SpawnRotation);}else{const FRotator SpawnRotation = GetControlRotation();// MuzzleOffset is in camera space, so transform it to world space before offsetting from the character location to find the final muzzle positionconst FVector SpawnLocation = ((FP_MuzzleLocation != nullptr) ? FP_MuzzleLocation->GetComponentLocation() : GetActorLocation()) + SpawnRotation.RotateVector(GunOffset);//Set Spawn Collision Handling OverrideFActorSpawnParameters ActorSpawnParams;ActorSpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButDontSpawnIfColliding;// spawn the projectile at the muzzleWorld->SpawnActor<ATrueFPSProjectProjectile>(ProjectileClass, SpawnLocation, SpawnRotation, ActorSpawnParams);}}}// try and play the sound if specifiedif (FireSound != nullptr){UGameplayStatics::PlaySoundAtLocation(this, FireSound, GetActorLocation());}projectileCount += 1;// try and play a firing animation if specifiedif (FireAnimation != nullptr){// Get the animation object for the arms meshUAnimInstance* AnimInstance = Mesh1P->GetAnimInstance();if (AnimInstance != nullptr){AnimInstance->Montage_Play(FireAnimation, 1.f);}}
}void ATrueFPSProjectCharacter::OnResetVR()
{UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition();
}void ATrueFPSProjectCharacter::BeginTouch(const ETouchIndex::Type FingerIndex, const FVector Location)
{if (TouchItem.bIsPressed == true){return;}if ((FingerIndex == TouchItem.FingerIndex) && (TouchItem.bMoved == false)){OnFire();}TouchItem.bIsPressed = true;TouchItem.FingerIndex = FingerIndex;TouchItem.Location = Location;TouchItem.bMoved = false;
}void ATrueFPSProjectCharacter::EndTouch(const ETouchIndex::Type FingerIndex, const FVector Location)
{if (TouchItem.bIsPressed == false){return;}TouchItem.bIsPressed = false;
}void ATrueFPSProjectCharacter::MoveForward(float Value)
{if (Value != 0.0f){// add movement in that directionAddMovementInput(GetActorForwardVector(), Value);}
}void ATrueFPSProjectCharacter::MoveRight(float Value)
{if (Value != 0.0f){// add movement in that directionAddMovementInput(GetActorRightVector(), Value);}
}void ATrueFPSProjectCharacter::TurnAtRate(float Rate)
{// calculate delta for this frame from the rate informationAddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}void ATrueFPSProjectCharacter::LookUpAtRate(float Rate)
{// calculate delta for this frame from the rate informationAddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}bool ATrueFPSProjectCharacter::EnableTouchscreenMovement(class UInputComponent* PlayerInputComponent)
{if (FPlatformMisc::SupportsTouchInput() || GetDefault<UInputSettings>()->bUseMouseForTouch){PlayerInputComponent->BindTouch(EInputEvent::IE_Pressed, this, &ATrueFPSProjectCharacter::BeginTouch);PlayerInputComponent->BindTouch(EInputEvent::IE_Released, this, &ATrueFPSProjectCharacter::EndTouch);//Commenting this out to be more consistent with FPS BP template.//PlayerInputComponent->BindTouch(EInputEvent::IE_Repeat, this, &ATrueFPSProjectCharacter::TouchUpdate);return true;}return false;
}
  1. 新建一个界面HUD


    新建一个绑定,绑定到TextBlock上,

    通过蓝图实现函数工功能
  2. 新建游戏模式TrueFPSProjectGameMode的蓝图BP_TrueFPSProjectGameMode,并且在蓝图中把HUD添加上去

aaa

更多推荐

UE4 第一人称游戏和界面操作交互

本文发布于:2024-03-10 01:10:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1726636.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:人称   界面   操作   游戏

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!