How to fix my raycast?

I’m making a building system right now.

I am trying to make a script that moves a part parallel to a surface. However, as you can see in the video below, it’s slightly inaccurate for some reason. If anyone is aware of a fix, feel free to let me know. Thank you!

Code:

local UserInputService = game:GetService ("UserInputService")

local Part = workspace:WaitForChild("MovePart")

local Player = game:GetService ("Players").LocalPlayer
local Camera = workspace.CurrentCamera

local Params = RaycastParams.new ()
Params.FilterType = Enum.RaycastFilterType.Exclude
Params.FilterDescendantsInstances = {Player.Character, Part}

UserInputService.InputChanged:Connect (function (input, gameProcessed)
	if gameProcessed or input.UserInputType ~= Enum.UserInputType.MouseMovement then
		return

	end

	local mouseLocation = UserInputService:GetMouseLocation ()

	local unitRay = Camera:ScreenPointToRay (mouseLocation.X, mouseLocation.Y)
	local result = workspace:Raycast (unitRay.Origin, unitRay.Direction * 500, Params)

	if result and result.Instance then
		local roundedPosition = Vector3.new (math.round (result.Position.X), math.round(result.Position.Y), math.round (result.Position.Z))

		game:GetService("TweenService"):Create(Part, TweenInfo.new(0.1), {Position = roundedPosition + result.Normal * (Part.Size / 2)}):Play()
	end
end)

Thanks again guys!! :smile:

seen this trick where you bump the y mouse location up by 26 pixels for some reason… try it out
might have something to do with the top bar idk

I’m not very sure, but using the tweens might cancel eachother out.
Try setting the position of the part.

Just tried this. Unfortunately it still yields the same results. Any further suggestions?

Just went into studio and tested out your script, except I changed
local unitRay = Camera:ScreenPointToRay (mouseLocation.X, mouseLocation.Y)
to
local unitRay = Camera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y)

and it was a bit more accurate than before.

I’m pretty sure Camera:ScreenPointToRay() accounts for the top bar, like what @syylvi was saying.

1 Like

Great job! That’s really interesting.
Great solution.

use viewportpointtoray instead of screen

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.