In this post I'm going to show you how to create latent Blueprint nodes that…
Raycasting is a special collision technique in which you emit a single ray (in this case at least!), with fixed length, origin and direction that has a Hit Result which contains information about the Object or Actor that the ray collided with.
For this post, I’m going to use a FirstPerson C++ Template. I will create a function in c++ that will be called in every frame. Let’s start!
Setting up the Character class
As I said above, I created a FirstPerson C++ template. Then, I opened the corresponding header file for my character and overrided the Tick function by typing:
void Tick(float DeltaTime) override;
Your character might have a different name depending on how you named your project, so in case you pasted the above code in your project change the name of the character’s class.
Before we go on and implement the logic of the Tick function, first let’s take a step back and provide more info about the single line raycasting.
Parameters of a Single Line Raycast
In order to perform a raycast, we need to know:
- The origin
- The end point
- The collision channel (which essentially is the channel that our ray is. For example, in this parameter you declare if you are looking only for static objects or really anything you want to)
- Additional parameters
Moreover, we need to declare a HitResult which contains all the information about what the ray has actually hit (if anything).
Here is a visual representation of an unsuccessful raycast:
And here is a visual representation of a successful raycast:
Performing a Single Line Raycast into the Tick function
Since we need to know the direction that the player is looking, the origin of our ray is going to be the actual position of our camera.
The end point of the ray is going to be an extension of a fixed distance, in the direction that the player’s camera is looking. To get the end point, we are going to use a function named GetForwardVector() which will provide us with a normalized vector with the direction of the camera. Because the vector is normalized, we are going to multiple it with a float number, which essentially is the length of our ray. After we get the said vector, we are going to add the origin of our ray, so that the end point is actually some units ( the length of our ray ) in front of the camera.
Before you type in the following code, include in the source file the following header:
This header includes the DrawDebugLine function I used in the code below so I can visualize the Raycast.
In order to perform the Raycast, type in the following code:
Now if you compile your code, press play, turn the camera a bit and Eject from the character so you can see the raycast drawn as seen below: