11.Adding Power to the Game
BatteryPickup.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 |
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Pickup.h"
#include "BatteryPickup.generated.h"
UCLASS()
class BATTERYCOLLECTOR_API ABatteryPickup : public APickup
{
GENERATED_BODY()
// Sets default values for this actor's properties
public:
ABatteryPickup();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
/**Override the WasCollected function_us Implementation
because it's a Bluepirnt Native Event*/
void WasCollected_Implementation() override;
/*Public way to access the battery's power level*/
float GetPower();
protected:
/*Set the amount of power the battery gives to the Character*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Power")
float BatteryPower;
};
|
cs |
23) BatteryPower에 접근하기 위한 public
28) 캐릭터에게 줄 power 양.
BatteryPickup.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 |
// Fill out your copyright notice in the Description page of Project Settings.
#include "BatteryCollector.h"
#include "BatteryPickup.h"
//Set Default values
ABatteryPickup::ABatteryPickup(){
BatteryPower = 150.0f;
}
void ABatteryPickup::BeginPlay()
{
Super::BeginPlay();
GetMesh()->SetSimulatePhysics(true);
}
void ABatteryPickup::WasCollected_Implementation(){
//Use the base pickup behavior
Super::WasCollected_Implementation();
//Destroy the battery
Destroy();
}
float ABatteryPickup::GetPower(){
return BatteryPower;
}
|
cs |
9)초기값
BatteryCollectorCharacter.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101 |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "GameFramework/Character.h"
#include "BatteryCollectorCharacter.generated.h"
UCLASS(config=Game)
class ABatteryCollectorCharacter : public ACharacter
{
GENERATED_BODY()
/** Camera boom positioning the camera behind the character */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class USpringArmComponent* CameraBoom;
/** Follow camera */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class UCameraComponent* FollowCamera;
/** Collection sphere */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class USphereComponent* CollectionSphere;
public:
ABatteryCollectorCharacter();
/** 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;
/**Accessor function for initial power*/
UFUNCTION(BlueprintPure, Category = "Power")
float GetInitialPower();
/**Accessor function for current power*/
UFUNCTION(BlueprintPure, Category = "Power")
float GetCurrentPower();
/*
*Function to update the character's power
*@param PowerChange This is the amount to change the power by, and it can be positive
*/
UFUNCTION(BlueprintCallable, Category = "Power")
void UpdatePower(float PowerChange);
protected:
/** Called for forwards/backward input */
void MoveForward(float Value);
/** Called for side to side input */
void MoveRight(float Value);
/**
* 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);
/** Handler for when a touch input begins. */
void TouchStarted(ETouchIndex::Type FingerIndex, FVector Location);
/** Handler for when a touch input stops. */
void TouchStopped(ETouchIndex::Type FingerIndex, FVector Location);
protected:
// APawn interface
virtual void SetupPlayerInputComponent(class UInputComponent* InputComponent) override;
// End of APawn interface
/*CAlled when we press a key to collect any pickups inside the CollectionSphere*/
UFUNCTION(BlueprintCallable, Category = "Pickups")
void CollectPickups();
/**The starting power level of our character*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Power")
float InitialPower;
private:
/**Current power level of our character*/
UPROPERTY(VisibleAnywhere, Category = "Power")
float CharacterPower;
public:
/** Returns CameraBoom subobject **/
FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; }
/** Returns FollowCamera subobject **/
FORCEINLINE class UCameraComponent* GetFollowCamera() const { return FollowCamera; }
/**return collectionsphere subobject*/
FORCEINLINE class USphereComponent* GetCollectionSphere() const { return CollectionSphere; }
};
|
cs |
84) 시작할때 power
89) 계속 업데이트될 현재 power
47)값은 양수또는 음수일수 있음, 이를 더해주는 방법으로 함수 한개만을 이용해서 값을 증가/감소 시킬수 있음
BatteryCollectorCharacter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176 |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "BatteryCollector.h"
#include "BatteryCollectorCharacter.h"
#include "Pickup.h"
//////////////////////////////////////////////////////////////////////////
// ABatteryCollectorCharacter
ABatteryCollectorCharacter::ABatteryCollectorCharacter()
{
// Set size for collision capsule
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->AttachTo(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->AttachTo(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
//create the collection sphere
CollectionSphere = CreateDefaultSubobject<USphereComponent>(TEXT("CollectionSphere"));
CollectionSphere->AttachTo(RootComponent);
CollectionSphere->SetSphereRadius(300.0f);
// 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++)
/**set a base power level for the character*/
InitialPower = 2000.0f;
CharacterPower = InitialPower;
}
//////////////////////////////////////////////////////////////////////////
// Input
void ABatteryCollectorCharacter::SetupPlayerInputComponent(class UInputComponent* InputComponent)
{
// Set up gameplay key bindings
check(InputComponent);
InputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
InputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);
InputComponent->BindAction("Collect", IE_Pressed, this, &ABatteryCollectorCharacter::CollectPickups);
InputComponent->BindAxis("MoveForward", this, &ABatteryCollectorCharacter::MoveForward);
InputComponent->BindAxis("MoveRight", this, &ABatteryCollectorCharacter::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
InputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
InputComponent->BindAxis("TurnRate", this, &ABatteryCollectorCharacter::TurnAtRate);
InputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
InputComponent->BindAxis("LookUpRate", this, &ABatteryCollectorCharacter::LookUpAtRate);
// handle touch devices
InputComponent->BindTouch(IE_Pressed, this, &ABatteryCollectorCharacter::TouchStarted);
InputComponent->BindTouch(IE_Released, this, &ABatteryCollectorCharacter::TouchStopped);
}
void ABatteryCollectorCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location)
{
// jump, but only on the first touch
if (FingerIndex == ETouchIndex::Touch1)
{
Jump();
}
}
void ABatteryCollectorCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location)
{
if (FingerIndex == ETouchIndex::Touch1)
{
StopJumping();
}
}
void ABatteryCollectorCharacter::TurnAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}
void ABatteryCollectorCharacter::LookUpAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}
void ABatteryCollectorCharacter::MoveForward(float Value)
{
if ((Controller != NULL) && (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 ABatteryCollectorCharacter::MoveRight(float Value)
{
if ( (Controller != NULL) && (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 ABatteryCollectorCharacter::CollectPickups(){
//Get all overlapping actors and store them in an array
//CollectionSphere와 오버랩되는 모든 액터를 배열로 받아옴
TArray < AActor* > CollectedActors;
CollectionSphere->GetOverlappingActors(CollectedActors);
//For each Actor we collected
for (int32 iCollected = 0; iCollected < CollectedActors.Num(); ++iCollected){
// Cast the actor to APickup
APickup* const TestPickup = Cast<APickup>(CollectedActors[iCollected]);
//If the cast is successful and the pickup is valid and active
if (TestPickup && !TestPickup->IsPendingKill() && TestPickup->IsActive()){
//call the pickup's wascollected function
TestPickup->WasCollected();
//deactivate the pickup
TestPickup->SetActive(false);
}
}
}
//reports starting power
float ABatteryCollectorCharacter::GetInitialPower(){
return InitialPower;
}
//reports current power
float ABatteryCollectorCharacter::GetCurrentPower(){
return CharacterPower;
}
void ABatteryCollectorCharacter::UpdatePower(float PowerChange){
CharacterPower = CharacterPower + PowerChange;
}
|
cs |
49,50)초기값
163~)추가
12.Powering Up the Character
05.08
BatteryPickup.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 |
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Pickup.h"
#include "BatteryPickup.generated.h"
UCLASS()
class BATTERYCOLLECTOR_API ABatteryPickup : public APickup
{
GENERATED_BODY()
// Sets default values for this actor's properties
public:
ABatteryPickup();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
/**Override the WasCollected function_us Implementation
because it's a Bluepirnt Native Event*/
void WasCollected_Implementation() override;
/*Public way to access the battery's power level*/
float GetPower();
protected:
/*Set the amount of power the battery gives to the Character*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Power")
float BatteryPower;
};
|
cs |
BatteryPickup.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 |
// Fill out your copyright notice in the Description page of Project Settings.
#include "BatteryCollector.h"
#include "BatteryPickup.h"
//Set Default values
ABatteryPickup::ABatteryPickup(){
BatteryPower = 150.0f;
}
void ABatteryPickup::BeginPlay()
{
Super::BeginPlay();
GetMesh()->SetSimulatePhysics(true);
}
void ABatteryPickup::WasCollected_Implementation(){
//Use the base pickup behavior
Super::WasCollected_Implementation();
//Destroy the battery
Destroy();
}
float ABatteryPickup::GetPower(){
return BatteryPower;
}
|
cs |
BatteryCollectorCharacter.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "GameFramework/Character.h"
#include "BatteryCollectorCharacter.generated.h"
UCLASS(config=Game)
class ABatteryCollectorCharacter : public ACharacter
{
public:
/**Function to update the character's power
*@param PowerChange This is the amount to change the power by, and it can be positive*/
UFUNCTION(BlueprintCallable, Category = "Power")
void UpdatePower(float PowerChange);
};
|
cs |
12,13) 캐릭터 파워 업데이트 기능추가
값은 양수또는 음수일수 있다
이를 더해주는 방법으로 함수 한개만을 이용해서 값을 증가/감소 시킬수 있음
BatteryCollectorCharacter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 |
#include "BatteryCollector.h"
#include "BatteryCollectorCharacter.h"
#include "Pickup.h"
#include "BatteryPickup.h"
//////////////////////////////////////////////////////////////////////////
// ABatteryCollectorCharacter
ABatteryCollectorCharacter::ABatteryCollectorCharacter()
{/**set a base power level for the character*/
InitialPower = 2000.0f;
CharacterPower = InitialPower;
}
void ABatteryCollectorCharacter::CollectPickups(){
//Get all overlapping actors and store them in an array
TArray < AActor* > CollectedActors;
CollectionSphere->GetOverlappingActors(CollectedActors);
//keep track of the collected battery power
float CollectedPower = 0;
//For each Actor we collected
for (int32 iCollected = 0; iCollected < CollectedActors.Num(); ++iCollected){
// Cast the actor to APickup
APickup* const TestPickup = Cast<APickup>(CollectedActors[iCollected]);
//If the cast is successful and the pickup is valid and active
if (TestPickup && !TestPickup->IsPendingKill() && TestPickup->IsActive()){
//call the pickup's wascollected function
TestPickup->WasCollected();
//Check to see if the pickup is also a battery
ABatteryPickup* const TestBattery = Cast<ABatteryPickup>(TestPickup);
if (TestBattery){
//increase the collected power
CollectedPower += TestBattery->GetPower();
}
//deactivate the pickup
TestPickup->SetActive(false);
}
}
if (CollectedPower > 0){
UpdatePower(CollectedPower);
}
}
|
cs |
19) 초기화
30) 아이템이 배터리인지 형변환으로 확인
31) 형변환 성공했으면
33)power 증가 시키고 GetPower 접근함수 써서 속에 든 값을 가져올수있게
39~)변동값이 있는지 확인
아이템 획득시 Character Power가 증가되는걸 볼수 있다.
'프로그래밍 > Unreal' 카테고리의 다른 글
[10]Battery Collector_ power에 따른 속도, 색변화 (0) | 2017.05.11 |
---|---|
[09]Battery Collector _ power 일정수준씩 감소시키기 (0) | 2017.05.11 |
[07]BatteryCollector_아이템습득 (0) | 2017.05.06 |
[06]Battery Collector _ spawn 결정(언제, 어디서, 무엇을) (0) | 2017.05.02 |
[06]Battery Collector_기초적인 아이템 물리(자유낙하) 적용 (0) | 2017.05.02 |