Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

[SOLVED] Make a model spawn in front of camera?

Asked by 7 years ago
Edited 7 years ago

So I want a model spawn in front of the camera on the surface nearest in the direction the camera is facing. I just need help getting the CFrame of that position as I am going to use model:SetPrimaryPartCFrame(newCFrame) but I can't find a way to set newCFrame to the position I want. I've looked into Raycasting but can't see a way to find the end CFrame of the ray, only the part it's hit but this will only allow me to spawn the model at that part's center. I've also looked around for the source of Studio's insert part script but have been unable to find it, this does exactly what I want it to do, spawn directly in front on the camera, on the nearest surface and if there isn't a surface then spawn at the position 0, 0, 0 and move the camera to over there. I'm terrible at Camera Manipulation but have still even tried using the camera's CFrame and using the look vector of it to just try and spawn it a few studs in front but never achieved what it was meant to.

I hope you can help, I wish I still had my code so I could put it here so it looks like less of a request but I got frustrated and didn't save any of what I did yesterday. Any help is appreciated but if it is just help it's better as comments so people don't think this has already been answered.

2 answers

Log in to vote
3
Answered by 7 years ago
Edited 7 years ago

The best way to find the world position at the centre of the camera is to use raycasting. You can cast a ray going from workspace.CurrentCamera.CFrame.p in the direction of workspace.CurrentCamera.CFrame.lookVector, like this:

local MyRay = Ray.new(workspace.CurrentCamera.CFrame.p, workspace.CurrentCamera.CFrame.lookVector * 1000) -- Make sure to multiply the direction vector for this case. 1000 is more than enough and I believe is the maximum.

then (and this is likely the part you were stuck with) you can get the position of the collision using the second return value of FindPartOnRay or FindPartOnRayWithIgnoreList:

local Part, Position  = workspace:FindPartOnRay(MyRay)

then finally set the position:

model:SetPrimaryPartCFrame(CFrame.new(Position))

Of course, this is only a simple example of how to do it, but it should help.

Ad
Log in to vote
0
Answered by 7 years ago

I do not know how can I use ray or other things to put spawn on surface, but I know getting CoordinateFrame of camera would help you much. You can use:

CF = game.Workspace.Camera.CoordinateFrame

in a server script or in command bar, or if players will use this while playing you can use

CF = game.Workspace.CurrentCamera.CoordinateFrame

in a local script.

Edit: Dang, IDidMakeThat answered this two minutes before while I was typing :/

Answer this question