#take damage in sun script

1 messages · Page 1 of 1 (latest)

misty stag
#

I'm trying to make a script to make a player slowly take damage when in sunlight, (so if a shadow is above them the player doesn't take damage), but I have little experience in actual scripting and after looking through dev forums have found basically little to nothing.

sacred pelicanBOT
#

studio** You are now Level 10! **studio

soft summit
#

one of those rare occasions chatgpt can probably write this for you. in short you'd need to do a raytrace between player and sunangle and if it doesn't hit anything then it is in line of sight of the sun and then just use this condition for applying damage

#

sunangle depends on time of day so, idk you can try to come up with that math yourself, chatgpt can probably give you that specific function

candid frost
#

There is no gain in generating shit

soft summit
candid frost
#

I rather learn than generate shit

soft summit
#

the rest is very simple straight forward raycast(sun_angle_formula()) then the rest is trivial

candid frost
#

Cool, I still prefer learning than generating shit

#

I’d probably not even be able to fix in the future

soft summit
candid frost
#

Nope

soft summit
#

and tbh if it gives bad math then yeah you just write your own, i'm sure google has the formula somewhere

boreal elk
#

What You'll Need
A Script inside ServerScriptService

Basic Raycasting setup

A loop to check players every few seconds

Script: Sunlight Damage System
Put this Script in ServerScriptService:

lua
Copy
Edit
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local DAMAGE_INTERVAL = 1 -- seconds between damage ticks
local DAMAGE_AMOUNT = 5 -- how much damage per tick
local RAY_HEIGHT = 1000 -- how high the sun is (adjust based on map)

-- Function to check if a player is in sunlight
local function isInSunlight(character)
if not character then return false end

local head = character:FindFirstChild("Head")
if not head then return false end

local origin = head.Position + Vector3.new(0, RAY_HEIGHT, 0)
local direction = Vector3.new(0, -RAY_HEIGHT, 0)

local rayParams = RaycastParams.new()
rayParams.FilterType = Enum.RaycastFilterType.Blacklist
rayParams.FilterDescendantsInstances = {character}

local result = workspace:Raycast(origin, direction, rayParams)

-- If ray hits the character's own head first, it's exposed to sun
if result and result.Instance:IsDescendantOf(character) then
    return true -- In sunlight
else
    return false -- In shadow
end

end

-- Damage loop
while true do
for _, player in pairs(Players:GetPlayers()) do
local character = player.Character
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
if humanoid and humanoid.Health > 0 then
if isInSunlight(character) then
humanoid:TakeDamage(DAMAGE_AMOUNT)
end
end
end
wait(DAMAGE_INTERVAL)
end