Mouse Hit Position is inaccurate

Im trying to make a tool that faces a cylinder in the direction the mouse faces. Problem is the aim is messed up depending on where its fired. Instead of being directly on the mouse its sorta just going in the direction.

Code:

RunServ.Heartbeat:Connect(function()
	if firing and hitbox then
		
		hitbox.CFrame = CFrame.new(char.HumanoidRootPart.CFrame.Position, mouse.Hit.Position) * CFrame.new(0,0, - hitbox.Size.X/2) * CFrame.Angles(0,math.rad(90),0)
			
	end
end)
1 Like

It looks like the cylinder is small. The distance from your character to Mouse.Hit is much larger than the length of your cylinder, giving the illusion that Mouse.Hit is inaccurate.

2 Likes

Yep it’s an illusion, here is the problem mathematically.

This is the perceived inaccuracy.

image

This is the trigonometric diagram

It’s caused because the cylinder hitbox is too short it’s not able to reach the mouse hit position as @Brickman808 said. The multiple options, one is to decrease the mouse.Hit default length of 1000 studs by creating a custom mouse function like the below

local userInput = game:GetService("UserInputService")
local Mouse = {}
local RAY_DISTANCE = 1000 -- default ray distance like mouse.Hit
local cam = workspace.CurrentCamera

function Mouse.HitPosition(raycastParams, distance)
	local mousePos = userInput:GetMouseLocation()
	local viewportMouseRay = cam:ViewportPointToRay(mousePos.X, mousePos.Y)
	local rayCastResult = workspace:Raycast(viewportMouseRay.Origin, viewportMouseRay.Direction * (distance or RAY_DISTANCE), raycastParams)
	local hitPosition
	if rayCastResult then
		hitPosition =  rayCastResult.Position
	else
		hitPosition = viewportMouseRay.Origin+viewportMouseRay.Direction * (distance or RAY_DISTANCE)
	end
	return hitPosition
end
return Mouse

second option is to rotate it further, and the third is to increase the length of the cylinder hitbox.

I believe the first option is the easiest one just adjust the length until it looks good.

10 Likes