Hello, I have recently been encountering an issue whilst trying to make my sword raycast script. The parts that are meant to visualize the raycast look fine and accurate, but what the raycast actually hits is incorrect and I’m not sure why.
In the video example, the dots are representing the points where the raycast is starting and ending, and a line is drawn inbetween them. The parts that you can see turning pink, however, are what the raycast is really hitting.
I’m not really sure what I’m doing wrong, so here’s a code snippet that does the raycast.
local raycastResult = workspace:Raycast(Attachment1.WorldPosition, prevPos, raycastParams)
local part = Instance.new("Part")
part.Parent = workspace
part.Anchored = true
part.Position = Attachment1.WorldPosition
part.Size = Vector3.new(0.5, 0.5, 0.5)
part.Name = ("start")
part.Color = Color3.new(0, 1, 0)
local part2 = Instance.new("Part")
part2.Parent = workspace
part2.Anchored = true
part2.Position = prevPos
part2.Size = Vector3.new(0.5, 0.5, 0.5)
part2.Name = ("end")
part.Color = Color3.new(1, 0, 0)
-- Create the visualizer part
local visualizer = Instance.new("Part")
visualizer.Anchored = true
visualizer.CanCollide = false
visualizer.BrickColor = BrickColor.new("Institutional white")
visualizer.Transparency = 0.75
visualizer.Parent = workspace.Rays
local raycastDistance = (prevPos - Attachment1.WorldPosition).magnitude
visualizer.Size = Vector3.new(0.3, 0.3, raycastDistance)
visualizer.CFrame = CFrame.new(prevPos, Attachment1.WorldPosition)
game:GetService("Debris"):AddItem(visualizer, 1)
if raycastResult then
local hitPart, hitPosition = unpack({raycastResult.Instance, raycastResult.Position})
print(hitPart)
hitPart.Color = Color3.new(1, 0.596078, 0.772549)
local hashum = hitPart.Parent:FindFirstChild("Humanoid") or hitPart.Parent.Parent:FindFirstChild("Humanoid") or hitPart.Parent.Parent.Parent:FindFirstChild("Humanoid")
if hashum then
local enemyHum = hashum
visualizer.BrickColor = BrickColor.new("Light red")
visualizer.Transparency = 0.5
if enemyHum.Health - damage <= 0 and math.random(0, 2) == 0 then
Handle.Kill:Play()
local neck = enemyHum.Parent.Torso:FindFirstChild("Neck")
if neck then
enemyHum.Parent.Torso.Neck:Destroy()
enemyHum.Parent.Head.Position = Vector3.new(enemyHum.Parent.Head.Position.X, enemyHum.Parent.Head.Position.Y + 0.5, enemyHum.Parent.Head.Position.Z)
end
end
Handle.HitPlayer:Play()
enemyHum:TakeDamage(damage)
TagHumanoid(enemyHum, player)
else
Handle.Hit:Play()
visualizer.BrickColor = BrickColor.new("Dark Baby blue")
visualizer.Transparency = 0.5
end
return true
end
end
prevPos = Attachment1.WorldPosition
Any help fixing my code would be much appreciated!