I was playing around with ray casting and I found some odd behavior. I don’t understand. This script was never meant for a game but just for practice and I expect it to bounce off of things and launch but it acts weird. Script is local in startcharscripts
I don’t know much about vector math and stuff but I would love to learn.
Script Below:
local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()
local head = plr.Character:WaitForChild("Head")
local maxBounces = 10
local laserParts = workspace:WaitForChild("LaserStuff")
function createPoint(pos)
local part = Instance.new("Part")
part.CanCollide = false
part.CanTouch = false
part.Transparency = 1
part.Locked = true
part.Name = "LaserBouncePoint"
part.Anchored = true
part.Parent = laserParts
local attachment = Instance.new("Attachment")
attachment.Parent = part
return part,attachment
end
function fireLaser()
laserParts:ClearAllChildren()
local params = RaycastParams.new()
params.FilterDescendantsInstances = {head.Parent, laserParts}
local headVector = head.CFrame.lookVector
local lastResult
local currentVector = headVector * 100
local lastPart = head
local lastHitPos = nil
local bounces = 0
repeat
local ray = workspace:Raycast(lastPart.Position, currentVector, params)
lastResult = ray
print(ray)
if ray then
currentVector = ray.Normal + (ray.Normal - currentVector) -- should be normal of reflection
currentVector *=100
print(currentVector)
local newPart, attach = createPoint()
local newPart2, attach2 = createPoint() -- Create the beam
if lastHitPos == nil then
newPart.Position = head.Position
else
newPart.Position = lastHitPos
end
lastHitPos = ray.Position
newPart2.Position = ray.Position
local newBeam = Instance.new("Beam")
newBeam.Parent = laserParts
newBeam.Attachment0 = attach
newBeam.Attachment1 = attach2
bounces +=1
end
until lastResult == nil or bounces >= maxBounces
print("done casting")
end
mouse.Button1Down:Connect(function()
fireLaser()
end)