This is the current code I have for the CFrame of my spatial query hitbox:
local hitbox = Instance.new("Part")
local offset = Vector3.new(10,0,0)
hitbox.CFrame = camera.CFrame + camera.CFrame.LookVector * offset.X + Vector3.new(0,offset.Y)
My game is locked on third person. This is what the hitbox looks like currently:
This is obviously very flawed. There are a few things I’m struggling to accomplish with this, since I’m not very good at figuring out the math.
First, what’s the best way to detect where the player is looking in this situation? I’m not sure if I should keep using the camera, or use something else.
I’m also not sure how to make the hitbox centered on the player, as you can see in the video the hitbox is off to the side due to the third person perspective.
And I’m also not sure how I would limit how far vertically the hitbox can go, so the player cant aim directly up or down.
Apologies if its a lot, as you can tell, I’m very novice at coding. I’ve looked through the forums as well as on YouTube, but haven’t found anything. Any help would be VERY appreciated!
First of all, this is a good attempt. Here are a few things that would resolve your current concerns:
-
The only way to detect where the player is looking at (as far as I’m aware) is using the camera’s CFrame.
-
To make the hitbox centered to the player, use the Player’s RootPart Position in the CFrame instead of the camera.
A CFrame is a matrix, it includes both positional and rotational data. Simply replace the positional data of the Camera CFrame with that of the RootPart’s Positional data and you should achieve a good result.
- You can make a copy of the Camera’s CFrame and clamp its up and down rotation to achieve this, and then get the LookVector of the modified CFrame:
Camera = workspace.CurrentCamera
x,y,z = Camera.CFrame:ToEulerAnglesYXZ() -- Get the rotation in Euler Angles
x = math.clamp(x, minRot, maxRot) -- Clamp the rotation
y = math.clamp(y, minRot, maxRot) -- Clamp the rotation
Modified = CFrame.new(Camera.CFrame.Position) * CFrame.fromEulerAnglesYXZ(x,y,z) -- Apply new rotation to the camera
-- Use the modifed version --
Its important to note that during the clamping, the degrees are in radians you can use math.deg()
to get the angle in degrees. This is also only example code meant to give you an idea of how to do this.
Hope this helped!