How to do real raycasting using the mouse


Following this question I realize that there is no real raycasting wrapper in UE4, or I don’t know it. Let me explain:

Imagine you want to do mouse picking. So you will basically use ConvertMouseLocationToWorldSpace to get the world mouse “position” and “direction”. Then execute a LineTraceByChannel and check the result.

Howere, this doesn’t work because the world mouse position calculated before is I think, the position on the projection plane. The mouse “direction” calculation is then based on this wrong position. Which leads to an incorrect camera to mouse direction.

So my question is, is there any utils in UE4 which permits to do raycasting from Camera position (aka GetPlayerCameraManager::GetActorLocation) ?

Is there anything important I should know about raycasting in UE4 that I missed ?

Thanks for reading, best regards.

Have you tried (GetPlayerController)->(GetHitResultUnderCursorByChannel)

In PlayerController.cpp , check these 2 functions “GetHitResultAtScreenPosition” and “GetHitResultUnderCursor” ,you can see how it’s implemented

1 Like

Thanks for the feedback. It seems that this fonction is pretty accurate and works well. The issue is that I have to set the mouse position manually, cause using the mouse is just for debug purpose, my actual input is a (X, Y) screen coordinate from an external library :D. But I saw that it could be done in C++. I will explore this way.

Otherwise, I did a “real” raycasting like the following blueprint. It’s not 100% accurate but it’s way more accurate that using the “World mouse direction”.


I just realize GetHitResultUnderCursorByChannel function can’t be use in networked project. Cause the server has no idea about the mouse position of each client right ?
It would probably be possible to send to the server the mouse position, then force the server mouse position, do the raycast, then send back the result to the client. But I think it’s a terrible idea :smiley:

On top of that, the server has probably no idea about the client camera properties, it wouldn’t sound logic that cameras are replicated.

So I actually think my first solution was the good one. (the following blueprint)

I will create a new question, clearer, to show my issue

I figured it out. I was just stopping my custom ray too close: 20kcm away from the start point while GetHitResultAtScreenPosition stop it at 100kcm away from the start point, which explains the small difference.

Thanks for you help