How can I get a random (direction)point Inside the crosshair [GUI]

I’m doing a crosshair for my gun, but I don’t get what I want to do because I suck at math

What I am trying to do is a function that gives me a direction towards a random point within the crosshair BUT🍑 that is from a basepart towards the random point in 3D, because the weapon is in third person

Anything helps :pray:

3 Likes

something like this

local camera = game.Workspace.CurrentCamera
local maxSpread = 20-- degrees

local function getRandomAngle(spread)
     spread *= 10
     return math.deg(math.random(-spread, spread) / 10)
end

local function getRandomPointInCrosshair()
     local crosshairRay = camera:ViewportPointToRay()
     local crosshairCFrame = CFrame.lookAt(crosshairRay.Origin, crosshairRay.Origin + crosshairRay.Direction)
     crosshairCFrame *= CFrame.Angles(0, getRandomAngle(maxSpread), getRandomAngle(maxSpread))
     local result = game.Workspace:Raycast(randomizedCameraAngle.Position, randomizedCameraAngle.lookVector * 300)
     if result then
          return result.Position
     end
end

edit: if it doesn’t spread vertically swap out the values for z from CFrame.Angles with the x instead

2 Likes
local angle = CFrame.Angles(0, 0, math.pi * 2 * math.random()) * CFrame.Angles(math.random() * spread, 0, 0)

where spread is spread size in radians.

And then you can do:

local direction = directionVector * angle

Sorry for replying so late, I fell asleep xd
What do you mean by directionVector?

My plan is to make the bullet come out of the “barrel” of the gun as shown in the image, not from the camera :sweat_smile:

yeah, you’d be raycasting to see where the bullet should be shot to, not raycasting the bullet

1 Like

OHHH OKAY I SEE!
What do you mean by randomizedCameraAngle?

(replied to myself lol)
it’s a function in the code snippet, it’s declared there
btw the way it’s written means the spread is gonna be relative to how far your camera is to your target (if I understood the example pic correctly), if your intent was instead to have it be relative to the shotgun muzzle lmk since we’d need to swap out a couple variables

1 Like

In short, this is what I’m trying to do:
robloxapp-20220912-1729072.wmv Srry is in .wmv

I didn’t understand what you mean by

:pleading_face:

Finally!!!
I could do it by myself :face_with_monocle::wine_glass:

local function GetSpreadDirection(Offset)	
	
	local RA = Offset * math.sqrt(math.random()) / 2.5
	local theta = math.random() * 2 * math.pi
	local XOff = RA * math.cos(theta)
	local YOff = RA * math.sin(theta)
	
	local CrossHairPos = camera:ScreenPointToRay(mouse.X + XOff, mouse.Y + YOff)
	
	return CrossHairPos.Direction
end

Offset is the Size.X.Offset of the crosshair


keep

4 Likes