I wanted to create my own raycast punch system but I was very stumped on how to do it since the one I made was buggy with it not working precisely and sometimes wouldn’t hit.
EDIT: Removed irrelevant code.
Local script raycast punching system
Limb variable directly refers to an attachment inside an actual character limb/body part. Also, there are no errors, this is more like a flawed system than a broken one.
local timeBeforeComboReset = 1.5 -- seconds
local raycastDistance = 2 -- studs
local player = game.Players.LocalPlayer; local character = player.Character or player.CharacterAdded:Wait()
local limbs = {character.RightHand.Attachment} -- I use a function to insert an attachment onto the hand beforehand.
local function raycastPunches(hitlist) -- most important function
for _, limb in pairs(limbs) do -- circulates through a table of limbs being used
local lastPos
local limbSizeY_DividedBy2 = limb.Parent.Size.Y/4
local configuredRaycastDistance = raycastDistance + limbSizeY_DividedBy2
local currentRayCount = 0
local function castRay(raycast)
if currentRayCount == 5 then return nil end
currentRayCount = currentRayCount + 1
local target, pos = workspace:FindPartOnRay(raycast, character)
if not target then
local subtractionVector = (limb.WorldPosition - pos) - Vector3.new(0, limbSizeY_DividedBy2, 0)
local newdistance = subtractionVector.Magnitude - configuredRaycastDistance
if newdistance > 0 then -- this seemingly never happens anyways
local rayFirstPos = lastPos ~= nil and (pos - lastPos) or pos
lastPos = pos
target, pos = castRay(Ray.new(rayFirstPos, subtractionVector.Unit * newdistance))
else -- frequently occurs
print("Attempted to ray into empty space")
end
end
return target, pos
end
local target, pos = castRay(Ray.new(limb.WorldPosition - Vector3.new(0, limb.Parent.Size.Y/1.5, 0), limb.CFrame.LookVector * raycastDistance))
if not target then return end
damageTarget(target, currentAttack.Damage, hitlist) -- sends to a function that checks the hitlist if the target is already in it, if not, will deal damage (by sending a request to a remote event to do it)
end
end```
Why I don't use Touched or the RaycastHitbox public module
- I don’t use Touched because it is very inefficient, this raycast system is as buggy at not hitting as the Touched event function is!
- I want to learn to make something without using a public module with someone else’s code. If I was asked to make someone a punching system for example, they certainly would rather have original code than unoriginal code. I do however use the module anyways but I am attempting to learn how to create my own raycast punching system now.
That being said, if anyone would know how I could fix up my script or even how I can design a better system, it’d be appreciated!