Raycasting + 2D bullet tracer logic

I have troubles trying to determine if a 2D particle / frame should be visible (depending on if something is in front of the ray)

Here is my code:

function update()

local vec1, visible = camera:WorldToScreenPoint(part1.Position)
local vec2, visible2 = camera:WorldToScreenPoint(part2.Position)

local x = vec1.X
local y = vec1.Y
local z = vec1.Z

local x2 = vec2.X
local y2 = vec2.Y
local z2 = vec2.Z

local ratio = 500

if (visible or visible2) then
	trace.Visible = true
	p1.Visible = true
	p2.Visible = true
else
	trace.Visible = false
	p1.Visible = false
	p2.Visible = false
end

local dist = math.sqrt(math.pow((x2 - x), 2) + (math.pow((y2 - y), 2)))
trace.Size = UDim2.new(0, dist, 0, ratio/((z+z2)/2))

p1.Position = UDim2.new(0, x, 0, y)
p2.Position = UDim2.new(0, x2, 0, y2)

p1.Size = UDim2.new(0, ratio/z, 0, ratio/z)
p2.Size = UDim2.new(0, ratio/z2, 0, ratio/z2)


--number math.atan2(number y, number x) 
--(x2 + x1) / 2, (y2 + y1) / 2
trace.Position = UDim2.new(0, (x2 + x)/2, 0, (y2 + y)/2)
local rotation = math.atan2((y2-y), (x2-x))
rotation = rotation * 180
rotation = rotation / math.pi
rotation = rotation
print(rotation)
trace.Rotation = rotation

end

Anyways, how can I determine if there is anything “blocking” the ray from the ray to the player’s camera view?

(In this example, the ray should not be visible because it is technically behind the player)

*note: within my code, I don’t have any method of determining whether or not the frame should be visible… I was hoping that someone could help me with the logic.

4 Likes

I didn’t know that existed, thanks. Anyways, instead of using 2D bullets, I decided to use “beam” objects. But thanks for teaching me about the GetPartsObscuringTarget Camera feature :slight_smile:

2 Likes