Help with WorldToScreenPoint

I have here a line of code that checks if a part is on screen or not on screen. How would I make it so :WorldToScreenPoint() wont see through walls while the player is looking at the part?

local children = game.Workspace.trip:GetChildren()
	local trip = game.Workspace.trip.trip
	for i = 1, #children do
		local pos, vis = workspace.CurrentCamera:WorldToScreenPoint(children[i].Position)

Whenever the script finds a part on screen, it can be seen from anywhere in the map THROUGH WALLS. Is there any method to prevent this?

Cast a ray from the camera towards the point in world space.

workspace:Raycast(camera.CFrame, (part.Position - workspace.CurrentCamera.CFrame))

If the raycast doesn’t return anything, the camera is either inside of the part or is too far away (iirc 5k studs is the limit).

If the raycast returns a part that isn’t the target part, there’s probably something obstructing it.

2 Likes

but this is a renderstepped loop, wont a ton of raycasts lag? Just asking because i’m not to familiar with raycasts

No, raycasts are very performant. Performance does degrade depending on the length of the ray but unless you’re doing like hundreds every frame you should be ok. You could span the casts out if you’re worried for performance (like every .1 seconds instead of every frame) but again that’s only if you really need it.

You could also cast shorter rays (ie do (part.Position - workspace.CurrentCamera.CFrame).Unit * length)) but I’m not too sure if the performance of calculating a unit vector in C would outweigh that of a long ray. You could try it and find out though.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.