Shooting projectile at mouse click in Top Down Game

Hi all!

I’m trying to get my projectile to shoot at the position of my mouse click. So far I have the projectile spawning and shooting but the launch direction is off. Im trying to use the hit result from the GetHitResultUnderCursor() function but this sends it flying off in a weird direction. Can anyone help me out with this?


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);
			}
		}
	}
}


You used Hit.ImpactPoint for the launch direction but what you really need is


(Hit.ImpactPoint - MuzzleLocation).GetSafeNormal()

which gives you the direction vector from the muzzle location to the impact point.

Thanks for help :slight_smile:

It works for clicks to the right of the player but when I click to the left it shoots up in the air again?

EDIT: I had the muzzle offset too close to my Character. I moved it out a bit and it works fine now :slight_smile: thanks so much.