Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Mouse.Hit.LookVector Not retriving the correct position?

Im trying to use RayCasting for the fist time in a while, and I could not find out what was going on. So I checked some of my numbers and It seems my problem does not lie with the ray itself but the actual numbers themselves

I initially tried to use a beam to test if I was getting my numbers correct.

GunFired.OnServerEvent:Connect(function(plr, MouseLV)
local EndPoint = MouseLV - Origin
local PreCalcEndPoint = EndPoint
	local BeamAchor = Instance.new("Part")
	BeamAchor.CanCollide = true
	BeamAchor.Transparency = 0
	BeamAchor.Anchored = false 
	BeamAchor.Position = Tool.MuzzelFlash.Position
	
	local OuterPart = Instance.new("Part", workspace)
	OuterPart.CanCollide = true
	OuterPart.Transparency = 0
	OuterPart.Anchored = false 
	OuterPart.Position = PreCalcEndPoint
	
	local AttachmentO = Instance.new("Attachment", BeamAchor)
	Beam.Attachment0 = AttachmentO
	
	local AttachmentI = Instance.new("Attachment", OuterPart)
	Beam.Attachment1 = AttachmentI
end)

Even though the beam does not work (I don't care all that much), the outer part shows me that for whatever reason I'm not retrieving entirely the correct position, and I can't tell why. (Also keep in mind this is not my entire code, only the relevant parts of it)

1 comment

0

What exactly are you trying to make? Raycast from the camera to the mouse position?

1 answer

✓ Accepted answer

You don't subtract the LookVector from the origin. Your code:

local EndPoint = MouseLookVector - Origin

When using the LookVector property, it returns a Unit vector (or the direction that the front of an object is facing). Simply subtracting the mouse's LookVector and the Origin doesn't give you the direction nor endpoint. An efficient way of getting the direction from the origin to the mouse is to use "Vector3.Unit". Here's how I would code it:

GunFired.OnServerEvent:Connect(function(plr, mouse)
	local dir = (mouse.Hit.Position - Origin).Unit * RANGE -- How far you want the raycast to go.

	local params = RaycastParams.new()
	params.FilterDescendantInstances = {plr.Character}
	params.FilterType = Enum.RaycastFilterType.Blacklist -- Ignores the character, use "Enum.RaycastFilterType.Whitelist" if you want the other way around.

	local raycastResult = workspace:Raycast(Origin, dir, params)
	
	if raycastResult then -- If the raycast hits something
		local part = raycastResult.Instance
		print(part.Name .. " has been hit by the raycast.")
	end
 end)

1 comment

0

Thanks for your help, and sorry for being so late on this. It appears to be working however I cant entirely be sure, is there any way I could visually represent the ray to determine if the code is working properly?

This discussion is preserved as it was. New answers, comments, and votes are closed.