I’m trying to get my character to shoot a projectile at where I click with my cursor in C++. Im using the top down template.
If I could get the position for the mouse click I could create a Vector from the player to the position and add this as velocity to the projectile.
The projectile flys towards the camera when I click in the position of the blue mouse click.
Function code.
void ARaiderCharacter::OnFire()
{
// Get the coordinates of the mouse from our controller
float LocationX;
float LocationY;
APlayerController* PlayerController = Cast<APlayerController>(GetController());
PlayerController->GetMousePosition(LocationX, LocationY);
FVector2D MousePosition(LocationX, LocationY);
FVector LaunchDir;
FHitResult Hit;
Controller->CastToPlayerController()->GetHitResultUnderCursor(ECC_Visibility, false, Hit);
if (Hit.bBlockingHit){
if (Hit.Actor != NULL){
LaunchDir = Hit.ImpactPoint;
}
}
// try and fire a projectile
if (ProjectileClass != NULL)
{
// Get the camera transform
FVector CameraLoc;
FRotator CameraRot;
GetActorEyesViewPoint(CameraLoc, CameraRot);
// MuzzleOffset is in camera space, so transform it to world space before offsetting from the camera to find the final muzzle position
FVector const MuzzleLocation = CameraLoc + FTransform(CameraRot).TransformVector(MuzzleOffset);
FRotator MuzzleRotation = CameraRot;
MuzzleRotation.Pitch += 0.0f; // skew the aim upwards a bit
UWorld* const World = GetWorld();
if (World)
{
FActorSpawnParameters SpawnParams;
SpawnParams.Owner = this;
SpawnParams.Instigator = Instigator;
// spawn the projectile at the muzzle
AProjectile* const Projectile = World->SpawnActor<AProjectile>(ProjectileClass, MuzzleLocation, MuzzleRotation, SpawnParams);
if (Projectile)
{
// find launch direction
FVector const LaunchDir = Hit.ImpactPoint;
//Projectile->InitVelocity(LaunchDir);
Projectile->InitVelocity(LaunchDir);
}
}
}
}