My raycast is only hitting the sky and baseplate

So I’m trying to code a 3rd person gun script, and when I shoot the raycast seems to hit the sky or baseplate. I’ve tried looking for resources but I couldn’t find any, I’ve also printed out the mousePos and it seems to go into the thousands of studs away from the shot. Here’s my script (I popped it into ChatGPT to properly arrange it because when I script its EXTREMELY messy.)

game.ReplicatedStorage.Shoot.OnServerEvent:Connect(function(player, mousePos)
	-- Ensure the player's character and gun exist
	local char = player.Character
	if not char or not char:FindFirstChild("Gun") then return end

	-- Get the gun and attachment
	local gun = char:FindFirstChild("Gun")
	local attachment = gun:FindFirstChild("Attachment")
	if not attachment then return end

	-- Enable the muzzle flash effects
	attachment.FlashFX.Enabled = true
	attachment.FlashFX2.Enabled = true

	-- Wait a short time before disabling the flash effects
	wait(0.1)
	attachment.FlashFX.Enabled = false
	attachment.FlashFX2.Enabled = false

	-- Perform raycasting from the gun's position to the mouse position
	local gunPos = attachment.Position
	local direction = (mousePos - gunPos).unit * 1000  -- Fire the ray in the direction of the mouse position

	-- Raycast
	local ray = Ray.new(gunPos, direction)
	local hitPart, hitPosition = workspace:FindPartOnRay(ray, char)  -- Ignoring the player's character

	-- Check if we hit something
	if hitPart then
		-- Create effects or apply damage (optional)
		print("Hit: " .. hitPart.Name)

		-- Example: Apply damage if the hit part is a humanoid
		local hitHumanoid = hitPart.Parent:FindFirstChild("Humanoid")
		if hitHumanoid then
			hitHumanoid:TakeDamage(10)  -- Adjust the damage value as needed
		end
	end
end)

Any help would be helpful, maybe ChatGPT broke my script when i told it to properly organize it or something.

1 Like

I’ve also asked ChatGPT what it could be because of the lack of resources. It wasn’t helpful it just told me to do debugging like printing out what the raycast hits.

1 Like

ive figured something else, when i shoot upward it hits random things

edit, ive figured another thing out. The problem lies in my script that makes the gun aim towards the mouse, when i disable it the gun aims properly

1 Like

nevermind, i fixed it using a hitbox module

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