I’m working on simple game Anti Tank Guided Missile, which the missile changes the direction according to the crosshair on the middle of screen controlled by user’s mouse.
Firstly, I guided the crosshair beside the far cube then i fired the missile with re-guided the crosshair on to the cube.
The problem is, the direction of missile was changed based on the crosshair but with large error rate ( Green Debug Line of the Missile in the video shows that problem )
PlayerController - AimAt Function
int32 OUT SizeX;
int32 OUT SizeY;
GetViewportSize(SizeX, SizeY);
FVector2D CrosshairPositionOnScreen = FVector2D(SizeX * 0.5, SizeY * 0.5);
if (DeprojectScreenPositionToWorld(CrosshairPositionOnScreen.X,
CrosshairPositionOnScreen.Y, Crosshair_3D_Location, Crosshair_3D_Direction)) {
if (!GetKorniteOperatorPawn()) return;
FVector OUT CameraLocation;GetKorniteOperatorPawn()->GetCameraLocation(CameraLocation);
auto StartLocation = CameraLocation;
auto EndLocation = StartLocation + Crosshair_3D_Direction * Range;
DrawDebugLine(GetWorld(), StartLocation, EndLocation, FColor::Red, false, -1, 0, 10);
}
PlayerPawn - Fire Missile Function:
FVector Location = FVector(GetActorLocation().X,
GetActorLocation().Y + 100, GetActorLocation().Z + 100);
FRotator Rotation = SceneCamera->GetComponentRotation();
if (!ensure(ATGMissle_BP)) { return; }
ATGMissle = GetWorld()->SpawnActor<AATGMissleActor>(
ATGMissle_BP,
Location,
Rotation
);
Actor - MissileActor lunched after firing by PlayerPawn - Tick Function:
auto PlayerController = Cast<AATGMPlayerController>(GetWorld()->GetFirstPlayerController());
if (!PlayerController) return;
auto CrosshairRotation = PlayerController->Crosshair_3D_Direction.Rotation();
auto ForwardVectorRotation = Missle->GetForwardVector().Rotation();
auto Rotation = CrosshairRotation - ForwardVectorRotation;
auto StartLocation = Missle->GetComponentLocation();
auto EndLocation = StartLocation + Missle->GetForwardVector() * 400000;
DrawDebugLine(GetWorld(), StartLocation, EndLocation, FColor::Green, false, -1, 0, 10);
if (!Missle) return;
Missle->AddRelativeRotation(Rotation);
auto Force = Missle->GetForwardVector() * Missle->GetMass() * Acceleration;
Missle->AddForce(DeltaTime * Force);