Pong in C++ – The Ball and The Score

I am continuing the development of a simple Pong game using Unreal Engine in C++.

Cleaning the Content

I realized that I did not need Blueprints for the GameMode and the Paddle. In the Pong1PGameMode.ccp constructor, I can declare APaddle as the default Pawn class. I can also directly place a Paddle in the level by dragging it from the C++ class.

I have also refactored the Pong1PGameMode to have it inheriting from a new PongGameMode generic class.

The Ball

I have created a new Ball class based on Actor. This ball has an InitialSpeed property and use Physics. It is moved by setting its Physics Linear Velocity:

 BallMesh->SetPhysicsLinearVelocity(LaunchDirection * InitialSpeed);

The LaunchDirection is a Vector specified when we want to start the ball moving.

The Ball is spawned in the BeginPlay() function of the GameMode and set to move right away toward the right direction.

The Score

I have create a GameState class to keep the scores. I have also created a GoalComponent class which can be added to the mesh of a goal line.

When the ball overlap this goal, it will call the GameState to increase the score of the player associated with that goal. The player is specified when setting the component in the mesh.

For now, the GameMode is in charge of modifying the TextRender when the score changes. I am thinking of creating a new component for each TextRender to react to an event generated by the GameState when the Score changes.  I have already created the event and it is broadcast when the score changes:

 DECLARE_EVENT_TwoParams(APongGameState, FScoreChangedEvent, const EPlayerEnum, const uint8);
 FScoreChangedEvent OnScoreChanged() { return ScoreChanged; }
 ScoreChanged.Broadcast(Player, Score);

Player is an Enum specified in GameState.h:

UENUM(BlueprintType)
enum class EPlayerEnum : uint8
{
 PE_1 UMETA(DisplayName = "Player 1"),
 PE_2 UMETA(DisplayName = "Player 2")
};

Next Step

Next, I am going to work on the Paddle AI.

About

Gamer

Tagged with:

Leave a Reply