How to spawn a character relative to player

I’m trying to spawn my ally character in a set position offset to the player, I really have no idea how to even designate the location period so at the moment they spawn at the world origin.

Here’s my current code

void AShooterCharacter::BeginPlay()
{
	Super::BeginPlay();

	if(AllyClass)
	{
		UE_LOG(LogTemp, Warning, TEXT("ally spawned"));
		Ally = GetWorld()->SpawnActor<AAlly>(AllyClass);
	}
}

Something like this would try to spawn your Ally +100 X co-ordinates over from the location of your shooter character (with an empty FRotator which you could replace with GetActorRotation() for example to make them face the same way as you)

void AShooterCharacter::BeginPlay()
{
	Super::BeginPlay();

	if (AllyClass)
	{
		if (UWorld* World = GetWorld())
		{
			FActorSpawnParameters SpawnParameters;
			SpawnParameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButDontSpawnIfColliding;
			FVector SpawnLocation = GetActorLocation() + FVector(100, 0, 0);
			Ally = World->SpawnActor<AAlly>(AllyClass, SpawnLocation, FRotator(), SpawnParameters);
			if (Ally)
			{
				UE_LOG(LogTemp, Warning, TEXT("ally spawned"));
			}
		}
	}
}

There are some other ways to try and collision test before you spawn your Ally to make sure it finds a good spot like capsule tracing or finding a random spot in navigable area around your character

FActorSpawnParameters also controls quite a few options you can customize further for your spawn FActorSpawnParameters | Unreal Engine 5.2 Documentation

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.