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.