How do I spawn a part in front of a player's head depending on where the camera's facing?

Hopefully this should be a quick question, just need some help with CFrame math.

I want to spawn a throwable object in front of the player’s head, depending on where the player’s camera is looking like this:

After Googling I’ve tried:

local throwOffset = CFrame.new(0,0,-5)
part.CFrame = head.CFrame * throwOffset

but obviously this only works horizontally, because the player’s head isn’t rotating up and down.

How do I “push” the offset relative to the camera’s rotation, rather than relative to the head’s cframe?

Thank you in advance!

1 Like

If you’re talking about spawning a part in front of the camera, you would just replace that script you had with the camera. What i’m guessing you want to do is this

local unit = (head.Position - camera.CFrame.p).Unit
part.CFrame = CFrame.new(head.Position, head.Position + unit*5)

This script gets the direction between the head and the camera, and directs a part 5 studs in the unit from the head.

1 Like

CFrame.LookVector might help too

I just tried it, and got some weird behavior because my game’s in Fortnite-esque third-person. I assume it’s because the camera’s position and the head are at an offset, so the part was spawning to the left of where it should be. If there was a way to do this sequence with CFrames:

  1. Set the CFrame to the player’s head
  2. Rotate the CFrame to be in line with the player’s camera rotation
  3. “Push” the CFrame by a set offset

That would be perfect.

Oh yes i can do that

Unformatted because im too lazy to

local x,y,z = camera.CFrame:ToEulerAnglesXYZ()
part.CFrame = (head.CFrame * CFrame.Angles(x,y,z)) * CFrame.new(0,0,5)

It might’ve been my implementation, but your solution seemed to rotate incorrectly. Not sure what the problem was.

Fortunately, I’ve discovered a solution on my own, which I’ll now post. Thank you for the help anyway! It was a good starting point.

Just found a solution!

local throwOffset = 5 --studs in front of head for part to spawn
local newPos = head.Position + camera.CFrame.lookVector*throwOffset
part.CFrame = CFrame.new(newPos,newPos+camera.CFrame.lookVector)
14 Likes