How do I add camera shake when an entity is near by?

Hi, I’m trying to add an effect were the camera would shake when an entity passes by, may someone assist me please?

4 Likes

Explanation


  • Create yourself a debounce of distance and true/false.
  • Make a loop to check if the magnitude of any entity is lower than the distance.
    • If so, it’ll shake the players screen with camera offset and math.random(-1,1).
    • If not, it’ll continue to check until an entity is near.

Code:


This is just an example so it won’t benefit your game. Change variables and stuff for your game.

local deb = false -- Debounce (Switch)

local maxDistance = 50 -- Distance threshold

function Check() -- Returns true if entity is near
    for _, npc in pairs(NPCFolder:GetChildren()) do
        if (npc.PrimaryPart.Position - game.Players.LocalPlayer.Character.PrimaryPart.Position).Magnitude <= maxDistance then
            return true
        end
    end
    return false
end

while task.wait() do
     if Check() then -- If entity is near it'll mark as true
         local x = math.random(-100,100)/100
         local y = math.random(-100,100)/100
         local z = math.random(-100,100)/100
         game.Players.LocalPlayer.Character.Humanoid.CameraOffset = Vector3.new(x,y,z)math.random(-1, 1) -- Shakes screen randomly
     else
         game.Players.LocalPlayer.Character.Humanoid.CameraOffset = Vector3.new(0,0,0) -- Resets camera
     end    
end
10 Likes
-- //StarterCharacterScripts\\
local RunService = game:GetService("RunService") -- A service used to make something happen each frame, etc.
local MaxDist = 50 -- Change it to whatever
local Speed = 0.004 -- The frequency of the shakes.
local Intensity = 10 -- The amount of intensity in the shake
local Humanoid = script.Parent:WaitForChild("Humanoid") -- The players humanoid.
RunService.RenderStepped:Connect(function() -- Runs a event each frame depending on the fps of the user.
    local EntityPosToPlayer = (game.Workspace.Entity.Position - script.Parent.HumanoidRootPart.Position).Magnitude -- Change the entity to your entity
	if EntityPosToPlayer < MaxDist then -- Checks if the player isn't too far
		local X = math.cos(os.clock() * 30) * 0.01 -- The cosine will return a number between 1 and -1, it also will return a value in a up and down manner, therefore a infinite value going up like os.clock would be useful
		local Y = math.sin(os.clock() * 10) * Speed -- Same explanation as the cosine one.
		workspace.CurrentCamera.CFrame = workspace.CurrentCamera.CFrame * CFrame.Angles(X,Y,0)
	end
end)
7 Likes

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