Weird Projectile Raycasting Behavior

Hello there programmers,

I’m attempting to make a projectile system that casts rays for hit detection. While the motion of the projectile is fine, the casted ray is behaving in a manner I’ve never seen before. As seen in the GIF below, you can see that the ray detects a collision nowhere near the cast direction:
https://gyazo.com/be2b76f77528a884586f3c1fe4cae2f3.mp4

Does anyone have a solution for this, the game file is down below, I’ll provide the entire script in the post as well so that you don’t have to download the file, if you don’t want to.

Launcher.rbxl (16.7 KB)

Thank you for you help!

local player = game:GetService("Players").LocalPlayer
local mouse = player:GetMouse()
local RS = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")

local tool = script.Parent
local Equipped = false
local Char = player.Character or player.CharacterAdded:Wait()

tool.Equipped:Connect(function()
	Equipped = true
end)
tool.Unequipped:Connect(function()
	Equipped = false
end)

local IgnoreList = {player.Character,workspace.IgnoreRays}

local function CastRay()
	tool.Handle.FireSound:Play()
	local Velocity = CFrame.new(tool.Handle.Position,mouse.Hit.p).LookVector * 250
	local Pos = tool.Handle.Position
	
	local p = Instance.new("Part",workspace.IgnoreRays)
	p.Anchored = true
	p.CanCollide = false
	p.Size = Vector3.new(0.5,0.5,3)
	p.Material = Enum.Material.Neon
	p.BrickColor = BrickColor.new("Deep orange")
	
	while true do
		local dt = RunService.RenderStepped:Wait()
		
		local NextPos = Pos + (Velocity * dt)
		
		local p2 = Instance.new("Part",workspace.IgnoreRays)
		p2.Anchored = true
		p2.CanCollide = false
		p2.Material = Enum.Material.Neon
		p2.BrickColor = BrickColor.new("Artichoke")
		
		local Dist = (Pos - NextPos).Magnitude
		p2.Size = Vector3.new(0.35,0.35,Dist)
		p.CFrame = CFrame.new(Pos,NextPos)
		p2.CFrame = CFrame.new(Pos,NextPos) * CFrame.new(0,0,-Dist/2)
		
		local ray = Ray.new(Pos,NextPos)
		local hit,ImpactPoint,SurfaceNormal = workspace:FindPartOnRayWithIgnoreList(ray,IgnoreList)
		
		if hit then
			local p3 = Instance.new("Part",workspace.IgnoreRays)
			p3.Anchored = true
			p3.CanCollide = false
			p3.Material = Enum.Material.Neon
			p3.BrickColor = BrickColor.new("Bright red")
			p3.CFrame = CFrame.new(ImpactPoint)
			p3.Size = Vector3.new(1,1,1)
			break
		else
			Pos = NextPos
			Velocity = Velocity - Vector3.new(0,workspace.Gravity * dt,0)
			p.CFrame = CFrame.new(Pos,NextPos)
		end
	end
end

mouse.Button1Down:Connect(function()
	if Equipped then
		CastRay()
	end
end)
4 Likes

Your Ray constructor takes a position and direction, not a start and end. Try:

local ray = Ray.new(Pos,NextPos - Pos)

3 Likes

Perfect, I had poked around the solution several times. Thank you!