Hello Unreal Engine community,
I am currently working on a top-down shooter project, and I want my character to always rotate towards the mouse position. However, I am facing a compilation error: “CPP_Player”: undeclared identifier. I have tried various solutions, but the error persists. Here is the code for the CPP_PlayerController.cpp and CPP_PlayerController.h files:
CPP_PlayerController.cpp:
#include "CPP_PlayerController.h"
#include "CPP_Player.h"
ACPP_PlayerController::ACPP_PlayerController()
{
PrimaryActorTick.bCanEverTick = true;
}
void ACPP_PlayerController::BeginPlay()
{
Super::BeginPlay();
ControlledPlayer = Cast<CPP_Player>(GetCharacter());
}
void ACPP_PlayerController::Tick(float DeltaTime)
{
FVector MouseVector = GetMouseVector();
// Get the character and calculate the direction vector from the character to the mouse position
if (ControlledPlayer)
{
FVector DirectionVector = MouseVector - ControlledPlayer->GetActorLocation();
DirectionVector.Z = 0.0f; // Ignore the Z-axis to only rotate on the XY plane
// Rotate the character towards the mouse position
if (DirectionVector.SizeSquared() > 0.0f) // Make sure the direction vector is not zero
{
FRotator TargetRotation = DirectionVector.Rotation();
ControlledPlayer->SetActorRotation(TargetRotation);
}
}
FString MouseVectorString = GetMouseVector().ToString();
// Print the vector in a debug message
GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, FString::Printf(TEXT("Mouse position: %s"), *MouseVectorString));
}
FVector ACPP_PlayerController::GetMouseVector()
{
// Get the current mouse position
FVector2D MousePosition;
GetMousePosition(MousePosition.X, MousePosition.Y);
// Get the world location of the mouse cursor
FVector MouseLocation, MouseDirection;
DeprojectScreenPositionToWorld(MousePosition.X, MousePosition.Y, MouseLocation, MouseDirection);
// Store the mouse location in a vector and return it
return FVector(MouseLocation.X, MouseLocation.Y, MouseLocation.Z);
}
CPP_PlayerController.h:
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "CPP_Player.h"
#include "CPP_PlayerController.generated.h"
/**
*
*/
class CPP_Player;
UCLASS()
class TOPDOWNLEVELSHOOTER_API ACPP_PlayerController : public APlayerController
{
GENERATED_BODY()
protected:
CPP_Player* ControlledPlayer;
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
ACPP_PlayerController();
virtual void Tick(float DeltaTime) override;
public:
FVector GetMouseVector();
};