Raycasting to see if sunlight is hitting the player

I’m trying to make something similar to a “vampire system” as such, where the player will burn if they stand in sunlight, but won’t burn at night or if they’re in a shadow.
I found a post from 2020 that said you can raycast from the sun to the player and see if the light is hitting them, but I’ve never used raycasting before so I need help with it.
I found this on the old post:

local Lighting = game:GetService("Lighting")
local SunDirection = Lighting:GetSunDirection()
1 Like
local Lighting = game:GetService("Lighting")
local SunDirection = Lighting:GetSunDirection()

local primaryPart = ...
local humanoid = ...
local sunrayLength = 300
local raycastParams : RaycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {character}
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist

local lengthOffset : number = primaryPart.Size.Y/2 + humanoid.HipHeight
local inShade : RaycastResult? = workspace:Raycast(primaryPart.Position - Vector3.new(0, lengthOffset, 0), SunDirection * sunrayLength, raycastParams)

if inShade then
	--They are in the shade
else
	--They are in the sun
end

It raycasts from the bottom of the player up to the direction of the sun

1 Like

Thank you! I’ll test this and let you know if it works.

1 Like

It only seems to be detecting it once, when I move into shade it doesn’t print “in shade”



and it also doesn’t print “in sun” if i walk back into the sun

the only thing i changed in your script is this

if inShade then
	print("in shade")
else
	print("in sun")
end
1 Like

If you copy pasted exactly what I gave you it will only run once. Try this:

local sunrayCheckInterval = 1 --every second it checks if you're in the shade or in the sun
task.spawn(function()
	while task.wait(sunrayCheckInterval) do
		local Lighting = game:GetService("Lighting")
		local SunDirection = Lighting:GetSunDirection()

		local primaryPart = ...
		local humanoid = ...
		local sunrayLength = 300
		local raycastParams : RaycastParams = RaycastParams.new()
		raycastParams.FilterDescendantsInstances = {character}
		raycastParams.FilterType = Enum.RaycastFilterType.Blacklist

		local lengthOffset : number = primaryPart.Size.Y/2 + humanoid.HipHeight
		local inShade : RaycastResult? = workspace:Raycast(primaryPart.Position - Vector3.new(0, lengthOffset, 0), SunDirection * sunrayLength, raycastParams)

		if inShade then
			--They are in the shade
		else
			--They are in the sun
		end
	end
end)
5 Likes

Thank you so much!

characterss

1 Like

Could this be used to make a kill mechanic, so you die if you leave the shade?

1 Like

it would work yes, but i’d probably increment the loop and make it faster if you’re doing it for an obby. Faster loop = more accurate detection

Alright. Thanks very much! :smiley: I will be using this then

1 Like

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