Third person raycasting direction

As of now, I’m trying to find the best way to get the direction I need to fire in for a third person gun.

When I fire, I pass over to the server a ViewportPointToRay returned ray:

CurrentCamera:ViewportPointToRay(CurrentCamera.ViewportSize.X/2, CurrentCamera.ViewportSize.Y/2)

(This is essentially the middle of the screen)

Then on the server, I do some calculations:

local ScreenPosition = (ScreenRay.Origin + (ScreenRay.Direction * GunData.ShotDistance))

local Forward = (ScreenPosition - Gun.Muzzle.Position).Unit
local Right = Forward:Cross(Vector3.FromAxis(Enum.Axis.Y))
local Up = Right:Cross(Forward)
				
local DirectionCFrame = CFrame.fromMatrix(Gun.Muzzle.Position, Right, Up)
local Direction = DirectionCFrame.LookVector * GunData.ShotDistance

Now the direction works, however it’s going diagonally through the position of the ScreenPosition.
Here’s a GIF of what’s happening:

I’d like it to go straight to the ScreenPosition, but I’m not sure how I can do that.
If any more information is required then I’ll be happy to supply it.

2 Likes

As I see, you are not using;

Mouse.Icon = ""

Instead, you are using a ViewPort, which maybe is the problem why it is not shooting where you want.

I use a UI, and the Viewport is just the Player’s Screen with GuiInset.
The middle of the Viewport (X/2, Y/2) is essentially the middle of the Player’s Screen.

This has nothing to do with the current direction, if I were to create a Part at ScreenPosition it’d be where I’d expect.

Hmh, then, I have nothing to do here, but anyways, I would suggest finding the direction with the Mouse (at least try what you get).

I’m not sure if i understand what you want to achieve.

Where’s a small illustration: