Get Forward Vector from Editor Camera Viewport

Hey guys,

I’m currently working on a tool within Unreal Engine 4 that allows our designer to quickly place Actors inside our levels, and hook certain variables onto it.

Currently I am at the point of spawning the Actors inside the level, and all is going well. However, I want the Actor to spawn in front of the camera’s viewport to access it quickly, and not let the Actor spawn at lets say (0,0,0).

I have been working on this issue for quite some time now, and I’m new to C++. (Yes I have knowledge and experience in Blueprints and with the Editor itself).

    //Init spawn location
	FVector spawnLocation = FVector(0, 0, 0);

    //Get viewport location
	UWorld* world = GetWorld();
	if (world != NULL)
	{
		auto viewLocations = world->ViewLocationsRenderedLastFrame;
		if (viewLocations.Num() != 0)
		{
                    //This works well. I get the exact location of the Editor Camera.
			spawnLocation = viewLocations[0];
		}

		FLevelEditorViewportClient* ViewportClient = GEditor->LevelViewportClients[0];
		FRotator Rotation = ViewportClient->GetViewRotation();
		FVector Direction = FRotationMatrix(Rotation).GetScaledAxis(EAxis::X);
		Direction.Normalize();
		spawnLocation += Direction * 600.0f;

            //The code below all result in Rotation (0,0,0), no matter what angle I have tilted the Camera to.
		UE_LOG(WaboLog, Warning, TEXT("ViewportClient %s"), *ViewportClient->LastEditorViewRotation.ToString());
		UE_LOG(WaboLog, Warning, TEXT("Rotation %s"), *Rotation.ToString());
	}

I’m really staring blanks right now. If somebody could point me into the right direction, that would be gladly appreciated!

Thanks in advance,

Wabo

You can do that:

    FEditorViewportClient* client = (FEditorViewportClient*)GEditor->GetActiveViewport()->GetClient();
	FVector editorCameraDirection = client->GetViewRotation().Vector();
    FVector editorCameraPosition = client->GetViewLocation();

    FVector spawnLocation = editorCameraPosition + (editorCameraDirection * 600.0f);

Next, you might want the object to collide with the groud or something before spawning? Anyway, in your code, it looks like you only want to spawn it 600 unit in front so that’s also viable.

Hope this helps!

Mick

Hey Mick,

Thank you very much for your reply, your solution works more than perfectly! :smiley:

Yes, you are right, I do intend to check with some sort of Line Trace if the Camera Viewport hits a floor (for the first lets say 3000 units), and if it doesn’t hit anything, then it will just spawn in front of the camera at lets say 600 units distance. But before I wanted to figure our how to do Line Tracing in C++, I figured I would take small steps at a time and first see how to even spawn an Actor from the Viewport forward. :).

I can’t stress enough how thankful I am. You really saved my a lot of headache and fooling around!

All the best,
Wabo