MyPlayer template
作者:互联网
1 // Fill out your copyright notice in the Description page of Project Settings. 2 3 #pragma once 4 5 #include "CoreMinimal.h" 6 #include "GameFramework/Character.h" 7 #include "Animation/AnimInstance.h" 8 #include "Sound/SoundCue.h" 9 #include "MyPlayer.generated.h"
10 class AWeapon_Pickup; 11 class AEnemy; 12 class UAnimMontage; 13 UENUM(BlueprintType) 14 enum class EMyPlayerState :uint8 { 15 MPS_NORMAL UMETA(DisplayName="Normal"), 16 MPS_SPRINTING UMETA(DisplayName = "Sprinting"), 17 MPS_ATTACKING UMETA(DisplayName = "Attacking"), 18 MPS_HURTING UMETA(DisplayName = "Hurting"), 19 MPS_DYING UMETA(DisplayName = "Dying"), 20 MPS_AMOUNT UMETA(DisplayName = "Amount") 21 }; 22 23 UCLASS() 24 class MYPROJECT2_API AMyPlayer : public ACharacter 25 { 26 GENERATED_BODY() 27 28 /** Camera boom positioning the camera behind the character */ 29 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) 30 class USpringArmComponent* CameraBoom; 31 32 /** Follow camera */ 33 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) 34 class UCameraComponent* FollowCamera; 35 36 public: 37 UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = Montage) 38 UAnimMontage* MyMontage; 39 UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = Materials) 40 UMaterialInstanceDynamic* playerSkinMaterial; 41 42 UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = PlayerDate) 43 USoundCue* GetHitSound; 44 UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = PlayerDate) 45 USoundCue* AttackSound; 46 UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = PlayerDate) 47 UParticleSystem* GetHitParticle; 48 public: 49 AMyPlayer(); 50 void IncreaseHitpoint(float); 51 void DecreaseHitpoint(float); 52 void IncreaseCoin(int); 53 void IncreaseStamina(float); 54 void DecreaseStamina(float); 55 void Die(); 56 57 58 void Sprint(); 59 void StopSprint(); 60 61 void Attack(); 62 UFUNCTION(BlueprintCallable, Category =Notify) 63 void NotifyAttackEnd(); 64 65 //arm relative 66 void SetNewWeapon(AWeapon_Pickup*curWeapon); 67 void LMBDown(); 68 void LMBUp(); 69 70 void SetPlayerState(EMyPlayerState StateType); 71 EMyPlayerState GetPlayerState(); 72 73 /** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */ 74 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera) 75 float BaseTurnRate; 76 77 /** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */ 78 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera) 79 float BaseLookUpRate; 80 81 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = playerData) 82 EMyPlayerState MainPlayerState; 83 84 UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = playerData) 85 AWeapon_Pickup* holdingWeapon; 86 87 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = playerData) 88 class AMyPlayerController* myPlayerController; 89 UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = playerData) 90 class AEnemy* TargetEnemy; 91 92 UFUNCTION(BlueprintCallable) 93 void NotifyAnim_HitEnd(); 94 95 96 97 98 //player get damage 99 virtual float TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser) override; 100 void ResetMaterialHurtFlag(); 101 102 103 104 //arm relative 105 AWeapon_Pickup* NewWeapon; 106 FTimerHandle HurtTimerHandle; 107 private: 108 109 bool bIsLMBDown; 110 bool bIsAttacking; 111 bool bGetHit=false; 112 113 protected: 114 115 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = playerData) 116 float currentSpeed; 117 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = playerData) 118 float maxRunSpeed; 119 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = playerData) 120 float maxSprintSpeed; 121 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = playerData) 122 float Hitpoint; 123 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = playerData) 124 float maxHitpoint; 125 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = playerData) 126 float stamina; 127 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = playerData) 128 float maxStamina; 129 float restTime; 130 bool bIntoRest; 131 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = playerData) 132 int32 coinCount; 133 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = playerData) 134 float StaminaLoss; 135 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = playerData) 136 bool bIsShiftDown; 137 /** Called for forwards/backward input */ 138 void MoveForward(float Value); 139 140 /** Called for side to side input */ 141 void MoveRight(float Value); 142 /** 143 * Called via input to turn at a given rate. 144 * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate 145 */ 146 void TurnAtRate(float Rate); 147 148 /** 149 * Called via input to turn look up/down at a given rate. 150 * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate 151 */ 152 void LookUpAtRate(float Rate); 153 void Jump() override; 154 155 // APawn interface 156 virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; 157 // End of APawn interface 158 159 public: 160 /** Returns CameraBoom subobject **/ 161 FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; } 162 /** Returns FollowCamera subobject **/ 163 FORCEINLINE class UCameraComponent* GetFollowCamera() const { return FollowCamera; } 164 165 protected: 166 // Called when the game starts or when spawned 167 virtual void BeginPlay() override; 168 169 public: 170 // Called every frame 171 virtual void Tick(float DeltaTime) override; 172 173 174 };
cpp file
// Fill out your copyright notice in the Description page of Project Settings. #include "MyPlayer.h" #include "MyPlayerController.h" #include "Pickup/Weapon_Pickup.h" #include "Enemy.h" #include "Animation/AnimMontage.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Components/InputComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/Controller.h" #include "GameFramework/SpringArmComponent.h" // Sets default values AMyPlayer::AMyPlayer() { // 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; GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input... GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate GetCharacterMovement()->JumpZVelocity = 600.f; GetCharacterMovement()->AirControl = 0.2f; // Create a camera boom (pulls in towards the player if there is a collision) CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller // Create a follow camera FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera")); FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm myPlayerController = nullptr; TargetEnemy = nullptr; // Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character) // are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++) MainPlayerState = EMyPlayerState::MPS_NORMAL; maxHitpoint = 100.0f; Hitpoint = maxHitpoint; maxStamina = 100.0f; stamina = maxStamina; restTime = 2.5f; bIntoRest = false; coinCount = 0; StaminaLoss = 10.0f; bIsShiftDown = false; bIsAttacking = false; bIsLMBDown = false; //initialize arm relative holdingWeapon = nullptr; NewWeapon = nullptr; MyMontage = nullptr; //effects GetHitSound = nullptr; GetHitParticle = nullptr; //maxSpeed = GetCharacterMovement()->GetMaxSpeed();//游戏运行后才能获取 maxRunSpeed = GetCharacterMovement()->MaxWalkSpeed;// maxSprintSpeed = maxRunSpeed + 500.0f; currentSpeed = GetCharacterMovement()->Velocity.Size();//same as GetMovementComponent()->Velocity.Size() } void AMyPlayer::IncreaseHitpoint(float amount) { if (Hitpoint + amount > maxHitpoint)Hitpoint = maxHitpoint; else AMyPlayer::Hitpoint += amount; } void AMyPlayer::DecreaseHitpoint(float amount) { if (Hitpoint - amount < 0.0f) { Hitpoint = 0.0f; Die(); } else AMyPlayer::Hitpoint -= amount; } void AMyPlayer::IncreaseCoin(int amount) { coinCount += amount; } void AMyPlayer::IncreaseStamina(float amount) { if (stamina + amount > maxStamina) { stamina = maxStamina; } else { stamina += amount; } } void AMyPlayer::DecreaseStamina(float amount) { if (stamina - amount < 0.0f) stamina = 0.0f; else AMyPlayer::stamina -= amount; } void AMyPlayer::Die() { UAnimInstance* AnimIns = GetMesh()->GetAnimInstance(); if (AnimIns && MyMontage) AnimIns->Montage_Play(MyMontage); AnimIns->Montage_JumpToSection("death", MyMontage); UE_LOG(LogTemp, Warning, TEXT("===========AMyPlayer: I'm Died! ==========! ")); } void AMyPlayer::Sprint() { bIsShiftDown = true; } void AMyPlayer::StopSprint() { bIsShiftDown = false; } void AMyPlayer::Attack() { UAnimInstance* AnimIns = GetMesh()->GetAnimInstance(); if (AnimIns && MyMontage) { UE_LOG(LogTemp, Warning, TEXT("===========Attacking ==========! ")); bIsAttacking = true; int sectionNum = FMath::RandRange(0, 2); switch (sectionNum) { case 0: AnimIns->Montage_Play(MyMontage); AnimIns->Montage_JumpToSection("attack1", MyMontage); break; case 1: AnimIns->Montage_Play(MyMontage); AnimIns->Montage_JumpToSection("attack2", MyMontage); break; case 2: AnimIns->Montage_Play(MyMontage); AnimIns->Montage_JumpToSection("attack3", MyMontage); break; } } } void AMyPlayer::NotifyAttackEnd() { bIsAttacking = false; UE_LOG(LogTemp, Warning, TEXT("===========AttackEnding ==========! ")); //if (bIsLMBDown) { // Attack(); //} } void AMyPlayer::SetNewWeapon(AWeapon_Pickup* curWeapon) { NewWeapon = curWeapon; } void AMyPlayer::LMBDown() { bIsLMBDown = true; if (NewWeapon&&NewWeapon != holdingWeapon) { if (holdingWeapon) { holdingWeapon->DestroyMyself(); holdingWeapon = nullptr; } holdingWeapon = NewWeapon; holdingWeapon->EquipStick(this); NewWeapon = nullptr; } else if (holdingWeapon) { UE_LOG(LogTemp, Warning, TEXT("===========Attack determine %d ==========! "),bIsAttacking); if (!bIsAttacking) { Attack(); } } } void AMyPlayer::LMBUp() { bIsLMBDown = false; } void AMyPlayer::SetPlayerState(EMyPlayerState StateType) { MainPlayerState = StateType; if (StateType == EMyPlayerState::MPS_SPRINTING) GetCharacterMovement()->MaxWalkSpeed = maxSprintSpeed; else GetCharacterMovement()->MaxWalkSpeed = maxRunSpeed; } EMyPlayerState AMyPlayer::GetPlayerState() { return AMyPlayer::MainPlayerState; } void AMyPlayer::NotifyAnim_HitEnd() { bGetHit = false; bIsAttacking = false; UE_LOG(LogTemp, Warning, TEXT("===========NotifyAnim_HitEnd ==========! ")); } float AMyPlayer::TakeDamage(float Damage, FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser) { if (Hitpoint - Damage < 0.0f) { Hitpoint = 0.0f; Die(); } else { bGetHit = true; AMyPlayer::Hitpoint -= Damage; UE_LOG(LogTemp, Warning, TEXT("===========Player Take Damage ==========! ")); playerSkinMaterial->SetScalarParameterValue("HurtFlag", 1.0f); GetWorldTimerManager().SetTimer(HurtTimerHandle, this, &AMyPlayer::ResetMaterialHurtFlag, 0.2f); AEnemy* enemy = Cast<AEnemy>(DamageCauser); FVector LaunchVector= enemy->GetActorForwardVector(); LaunchVector.X *= 700.0f; LaunchVector.Y *= 700.0f; LaunchVector.Z += 250.0f; LaunchCharacter(LaunchVector, true, true); UAnimInstance* AnimIns = GetMesh()->GetAnimInstance(); if (AnimIns && MyMontage) { AnimIns->Montage_Play(MyMontage); AnimIns->Montage_JumpToSection("Hit_front", MyMontage);//so sometimes "end" notify will be not call } } return Damage; } void AMyPlayer::ResetMaterialHurtFlag() { playerSkinMaterial->SetScalarParameterValue("HurtFlag", 0.0f); } void AMyPlayer::MoveForward(float Value) { if (Value) if ((Controller != nullptr) && (Value != 0.0f)) { // find out which way is forward const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get forward vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); AddMovementInput(Direction, Value); } } void AMyPlayer::MoveRight(float Value) { if (Value) if ((Controller != nullptr) && (Value != 0.0f)) { // find out which way is right const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get right vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); // add movement in that direction AddMovementInput(Direction, Value); } } void AMyPlayer::TurnAtRate(float Rate) { if (Rate) AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void AMyPlayer::LookUpAtRate(float Rate) { if (Rate) AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); } void AMyPlayer::Jump() { Super::Jump(); } // Called when the game starts or when spawned void AMyPlayer::BeginPlay() { Super::BeginPlay(); myPlayerController = Cast<AMyPlayerController>(GetController()); playerSkinMaterial = GetMesh()->CreateAndSetMaterialInstanceDynamic(0); //look in BP_MyPlayer build-in component Mesh-> Materials } // Called every frame void AMyPlayer::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (bIntoRest) { restTime -= DeltaTime; } if (restTime <= 0) { bIntoRest = false; restTime = 2.5f; } if (bIsShiftDown) { currentSpeed = GetCharacterMovement()->Velocity.Size(); if (currentSpeed >= maxRunSpeed - 3 && !bIntoRest) { SetPlayerState(EMyPlayerState::MPS_SPRINTING); DecreaseStamina(StaminaLoss * DeltaTime); //UE_LOG(LogTemp, Warning, TEXT("=======MPS_SPRINTING=========%f"), DeltaTime); } else { SetPlayerState(EMyPlayerState::MPS_NORMAL); IncreaseStamina(StaminaLoss / 3 * DeltaTime); //UE_LOG(LogTemp, Warning, TEXT("=======MPS_NORMAL=========")); } } else { IncreaseStamina(StaminaLoss * DeltaTime); SetPlayerState(EMyPlayerState::MPS_NORMAL); } //UE_LOG(LogTemp, Warning, TEXT("=======CurrentSpeed: %f========="), GetCharacterMovement()->GetMaxSpeed()); if (stamina <= 0.0f)bIntoRest = true; if (TargetEnemy) { myPlayerController->enemyPosition = TargetEnemy->GetActorLocation(); } } // Called to bind functionality to input void AMyPlayer::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); // Set up gameplay key bindings check(PlayerInputComponent); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &AMyPlayer::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); PlayerInputComponent->BindAction("Sprint", IE_Pressed, this, &AMyPlayer::Sprint); PlayerInputComponent->BindAction("Sprint", IE_Released, this, &AMyPlayer::StopSprint); PlayerInputComponent->BindAction("LMButton", IE_Pressed, this, &AMyPlayer::LMBDown); PlayerInputComponent->BindAction("LMButton", IE_Released, this, &AMyPlayer::LMBUp); PlayerInputComponent->BindAxis("MoveForward", this, &AMyPlayer::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &AMyPlayer::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 joystick PlayerInputComponent->BindAxis("TurnRate", this, &AMyPlayer::TurnAtRate); PlayerInputComponent->BindAxis("LookUpRate", this, &AMyPlayer::LookUpAtRate); }
标签:Category,UPROPERTY,MyPlayer,void,float,AMyPlayer,template,VisibleAnywhere 来源: https://www.cnblogs.com/shorts-shorts-shorts/p/16273734.html