Sunday, July 9, 2017

Playing a sound along a beam particle in UE4

Hey guys - something I've always wondered how to do was to play a sound along UE4's built in beam particle component. There is nothing built into the editor for it, so I decided I'd do it myself since Epitasis use's lots of lasers everywhere.

Its basically just a bunch of vector math. The following code will help you grab the nearest point on a finite line to the player, which will be used to update the audio component location. This code is of course, called while the laser beam is active, and updates frequently enough.

Here it is, in native UE4 C++ code:

FVector line = (RV_Hit.Location - Start);
float lineSize = line.Size();

FVector v = PlayerLoc - Start;
float d = Dot3(v, line);
d = FMath::Clamp(d, 0.0f, lineSize);

FVector pointOnLine = Start + line * d;

(Where Start is a FVector used for the starting location for the line trace RV_Hit)

Since beams can also be interrupted in the game, I'm doing a line trace (hence the RV_Hit.Location) to wherever the beam currently ends, from its initial starting location. PlayerLoc is simply grabbed before by doing:

FVector PlayerLoc = GetWorld()->GetFirstPlayerController()->GetPawn()->GetActorLocation();

From doing this, you can use the FVector pointOnLine to update the location/transform of the audio component. This way, the audio will always sound close on the laser beam emitter. Its also clamped as you can see, so it only sticks between the two points - it doesn't keep going as it would with a infinite line. I hope this helps someone.

Big kudos to lordofduct over on the Unity forums, where I used his algorthims to help facilitate this for UE4. Yay!

No comments:

Post a Comment