How do I detect distance between player and ground x units in front of player
I'm working on a game where the character can glide from high places. I've been thinking about the controls and how "Glide mode" would be activated, and the behavior I'd like is when the player jumps off of a ledge, the engine knows that the player would be falling for a certain distance and automatically activate a different jump animation to transition into glide mode. I was thinking that having a variable that tracked the distance from the ground a number of units in front of the player equal to the lateral distance of the player's jump would give me the information I need to do this, but I have no idea how to blueprint this. I'm very new to UE4 in general, so please be specific. Thanks very much!
The easiest way to do this would be to do a line trace straight down from a point in front of the player character. If you get the hit location and subtract it from the source of the line trace, and then get the difference in Z, you'll have your distance to the ground as a float.
Here's an image of what it might look like in your character Blueprint:
I created a Sphere Component in the Components tab and called it LineTraceStart. On Begin Play, it takes that component and Sets Relative Position (it's location relative to the Root, in this case the Capsule Component) to the vector Distance From Player. You can just as easily position the component in the Components tab to the distance you would like it in front of the player, but I set it up this way so that I can adjust the DistanceFromPlayer vector variable during play if I want. For this, though, I simply set the default value of the vector variable to 0,0,300 to place it a bit in front of the character.
Then on Event Tick, I used Line Trace by Channel. I get the LineTraceStart component's World Location (you might need to turn Context Sensitive off to find this in 4.5.1) for the Start input, and for the End input I subtract a vector value for the distance I want the trace to go. For this, I used a vector variable again and set its default value to 0,0,1000 to give it a nice long trace, but you may need to set this higher depending on how high your character will be.
You can adjust the Trace Channel later, if you want, but Visibility is good to start with. Later, you may want to create a custom Trace Channel (Project Settings > Collision) and set it to only see certain types of actors (so it doesn't calculate clouds or trees for distance).
Then I used the Out Hit and Break Hit Result to get the Location of the trace hit. Subtract that from the LineTraceStart's World Location to get the difference between the two locations, Break Vector to get the Z value of that difference, and there's your distance variable!
Hope that helps! Let me know if you have any questions.
answered Nov 19 '14 at 11:58 PM
Follow this question
Once you sign in you will be able to subscribe for any updates here