Hey! I’m trying to learn raycasting to later on build a sandbox build system. I stole some code from a model and it miraculously worked, could anyone tell me why? It’s something to do with workspace.CurrentCamera:ScreenPointToRay(mouse.X, mouse.Y, 1)
instead of what I previously had of mouse.Origin.Position
. So here are my questions:
- How does
workspace.CurrentCamera:ScreenPointToRay()
work? - This is kind of random but, how would you lock the part position to a grid, like say 2x2 studs?
- Is there a better way to achieve what I’m doing?
Here is my full code:
local runService = game:GetService("RunService")
local repStorage = game:GetService("ReplicatedStorage")
local players = game:GetService("Players")
local player = players.LocalPlayer
local mouse = player:GetMouse()
local ground = workspace.Ground
local buttonPressed = false
runService.RenderStepped:Connect(function()
if buttonPressed then
local target = mouse.Hit.Position
local unit = workspace.CurrentCamera:ScreenPointToRay(mouse.X, mouse.Y, 1)
local raycastResults = workspace:Raycast(unit.Origin, unit.Direction*10000)--workspace:Raycast(origin, distance)
print(raycastResults)
if raycastResults.Instance and raycastResults.Instance == ground then
local part = workspace.HoverPart
part.Position = Vector3.new(target.X, 1.5, target.Z) --mouse.Hit.Position
part.Color = Color3.new(0, 1, 0)
end
end
end)
game:GetService("UserInputService").InputBegan:Connect(function(input)
if input.KeyCode == Enum.KeyCode.E then
buttonPressed = not buttonPressed
end
end)
mouse.Button1Down:Connect(function()
if buttonPressed then
local clone = workspace.HoverPart:Clone()
clone.Parent = ground
clone.Transparency = 0
clone.Color = Color3.new(163, 162, 165)
clone.CanCollide = true
end
end)