Skip to content

Instantly share code, notes, and snippets.

@crash987
Created June 27, 2018 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crash987/7d527c300555bcdd90fbeae0adab5acc to your computer and use it in GitHub Desktop.
Save crash987/7d527c300555bcdd90fbeae0adab5acc to your computer and use it in GitHub Desktop.
Tank Player Controller
// Fill out your copyright notice in the Description page of Project Settings.
#include "TankPlayerController.h"
#include "GameFramework/Actor.h"
#include "GameFramework/Pawn.h"
#include "Engine/World.h"
#include "GameFramework/Controller.h"
void ATankPlayerController::BeginPlay()
{
Super::BeginPlay();
auto ControlledTank = GetControlledTank();
if (!ControlledTank)
{
UE_LOG(LogTemp, Warning, TEXT("PlayerController Begin Play"));
}
else
{
UE_LOG(LogTemp, Warning, TEXT("PlayerController possessing: %s"), *(ControlledTank->GetName()))
}
}
ATank * ATankPlayerController::GetControlledTank() const {
return Cast<ATank>(GetPawn());
};
void ATankPlayerController::AimTowardsCrosshair()
{
if (!GetControlledTank()) { return; }
FVector HitLocation;
if (GetSightRayHitLocation(HitLocation))
{
GetControlledTank()->AImAt(HitLocation);
}
}
// Called every frame
void ATankPlayerController::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
AimTowardsCrosshair();
}
bool ATankPlayerController::GetSightRayHitLocation(FVector& HitLocation) const
{
//Find the crosshair position in pixels coordinates
int32 ViewPortSizeX, ViewPortSizeY;
GetViewportSize(ViewPortSizeX, ViewPortSizeY);
auto ScreenLocation = FVector2D(ViewPortSizeX * CrossHairXLocation, ViewPortSizeY * CrossHairYLocation);
FVector LookDirection;
if (GetLookDirection(ScreenLocation, LookDirection))
{
GetLookVectorHitLocation(LookDirection, HitLocation);
}
return false;
}
bool ATankPlayerController::GetLookDirection(FVector2D ScreenLocation, FVector& LookDirection) const
{
FVector CameraWorldLocation;
return DeprojectScreenPositionToWorld(ScreenLocation.X, ScreenLocation.Y, CameraWorldLocation, LookDirection);
}
bool ATankPlayerController::GetLookVectorHitLocation(FVector LookDirection, FVector&HitLocation) const
{
FHitResult HitResult;
auto StartLocation = PlayerCameraManager->GetCameraLocation();
auto EndLocation = StartLocation + (LookDirection * LineTraceRange);
if (GetWorld()->LineTraceSingleByChannel(HitResult, StartLocation, EndLocation, ECollisionChannel::ECC_Visibility))
{
HitLocation = HitResult.Location;
return true;
}
HitLocation = FVector(0);
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment