Cast ray from Part, using direction of the mouse, until the ray hits a certain Z position?

I’m trying to position a model on the players mouse, BUT I just want it on their mouse X and Y position so its Z position should never change. I have a custom camera object (it’s just a floating part that gets moved around in local scripts and the players CurrentCamera.CFrame is set to that parts CFrame).

Now basically I want to cast a ray from that Camera object to this Model I’m movings Z position and the mouses X and Y position. Then that final X,Y position is where I will move the model and its Z position will always stay the same. This will be in a RenderStep function.


--This is my custom camera part I mentioned:
local Cam = game.Workspace:WaitForChild("TitleScreen"):WaitForChild("TitleCam")
local Mouse = game.Players.LocalPlayer:GetMouse()

RunService.RenderStepped:Connect(function()
	if mouseModel ~= nil then--'mouseModel' is the model I'm trying to move. This if statement just makes sure the player has one. I've tested this and know this part works fine thus far.
		--I want to update this models X and Y position in here every frame as I explained prior
		local ray = workspace:Raycast(Cam.Position,Mouse.UnitRay.Direction,rayParams)
		--This just returns nil so I'm doing it wrong I don't know how to get a ray to just go until a certain Z position
	end
end)

Any help would be appreciated

1 Like

The slope of any direction vector is it’s rise over it’s run:

local V3 = Vector3.new
local slope = dir.Z / (dir * V3(1, 1, 0)).Magnitude

The amount of run needed to get a specific rise is then

local targetZ = 0 --or whatever you want
local distToTargetZ = startZ * slope

and if you want the point where the target Z coordinate is reached, you’d do

local pointWithTargetZ = startPoint + dir * distToTargetZ

Hope this helps. Can’t test ATM so it might not work :sweat_smile:

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