Hello so Im currently having an issue on making a solution for when a raycast returns nil and still get the position Ive followed this Topic it works but the part where the raycast is nil the position is not accurate
Video Demonstration
local Caster = self.Caster
local CasterChar = Caster.Character
local Direction = (MousePos - CasterChar.RightHand.Position).Unit * 30
local Origin = CasterChar.RightHand.Position
local Rayresult = workspace:Raycast(Origin,Direction,self.Params)
local FinalPos
if Rayresult then
FinalPos = Rayresult.Position
else
FinalPos = Origin + Direction
end
local Part = Instance.new("Part")
Part.Parent = workspace
Part.Position = FinalPos
Part.CanQuery = false
Part.CanCollide = false
Part.Anchored = true
Ill appreciate any help!
It seems you used my topic to make the cast. I was wondering what did you use to get the mouse position?
The code looks correct to me, so can you explain what you mean when you say the position is “not correct”? What exactly do you want it to do?
hello im a bit late but the part that get spawned in is not accurate to where the mouse cursor is hovering
Mouse.Hit.Position is what I use to get the mouse position
This is because of angles and mouse raycast. The mouse casts a ray thousands of studs away. If it did not hit anything, it would just return its final position.
As you can see, the Mouse ray extends far far away, and the workspace:Raycast
tries to follow the mouse.Position.
If you limit the Mouse ray:
In this example, I limit the Mouse ray to 100 studs, thus the mouse.Position is shorter. When the workspace:Raycast
followed it, it looks more real.
1 Like
Did not mean to rhyme it, but anyways.
The solution is to make a custom Mouse ray. The advantages of using a custom Mouse ray is you can use RaycastParams, have custom results and isn’t thousands of studs away.
This is an example, you can change it however you want:
local char = plr.Character or plr.CharacterAdded:Wait()
local cam = workspace.CurrentCamera
local MAX_DISTANCE = 256 -- Max distance; You can change this
local params = RaycastParams.new()
params.FilterDescendantsInstances = {char} -- Add other stuff to ignore
local function MouseRay()
local Ray = cam:ScreenPointToRay(mouse.X,mouse.Y)
local origin, dir = Ray.Origin, Ray.Direction * MAX_DISTANCE
local result = workspace:Raycast(origin, dir, params)
if result then
return {
Hit = CFrame.lookAt(result.Position,result.Position+result.Normal),
Target = result.Instance,
Distance = result.Distance
}
else
local hit = origin+dir
return {
Hit = CFrame.lookAt(hit, hit+dir),
Target = nil,
Distance = MAX_DISTANCE
}
end
end
1 Like