attempt to index nil with health - lua

i am making a health bar to my humanoid/enemy but it keeps saying attempt to index nil with health
here is the code:
local Humanoid = script.Parent.Parent.Parent.Parent.Parent:FindFirstChild("Humanoid")
while true do
wait(0.1)
if Humanoid.Health <= 100 then
script.Parent.Healthbar.BackgroundColor3 = Color3.fromRGB(17, 255, 0)
end
if Humanoid.Health <= 50 then
script.Parent.Healthbar.BackgroundColor3 = Color3.fromRGB(255, 255, 0)
end
script.Parent.Healthbar.BackgroundColor3 = Color3.fromRGB(255, 0, 0)
end
script.Parent.HealthNum.Text = math.floor(Humanoid.Health) .. " / " .. math.floor(Humanoid.MaxHealth)
local pie = (Humanoid.Health / Humanoid.MaxHealth)
script.Parent.Healthbar.Size = UDim2.new(pie, 0, 1, 0)
end

Related

my frontflip backflip mechanic is not working as intended. Where should my variables go?

I don't know where to put the variables.
local frontflips, backflips = 0, 0
local upVector = cv.DesiredCF.UpVector
local lastDirection = "None"
-- local process = "None" -- FRontflip or backflip
local physics; physics = game:GetService("RunService").Heartbeat:Connect(function()
local lookVector = cart.PrimaryPart.CFrame.LookVector
local dotProduct = lookVector:Dot(upVector)
if ( math.abs(dotProduct) < .3) then
--// Facing downwards
if (lastDirection == "backflip") then
backflips = backflips + 1
frontflips = math.clamp(frontflips - 1, 0, 10)
elseif lastDirection == "frontflip" then
frontflips = frontflips + 1
backflips = math.clamp(backflips - 1, 0, 10)
end
lastDirection = "None"
elseif (dotProduct > .8) and lastDirection == "None" then
--// In the process of a back-flip
lastDirection = "backflip"
elseif dotProduct < -.8 and lastDirection == "None" then
lastDirection = "frontflip"
end
-- warn("Dot is ",dotProduct, " and ",lastDirection)
end)
When I do 1 frontflip it tells me
But now when I do 2 frontflips it tells me I only did 1.
If I remove the
frontflips = math.clamp(frontflips - 1, 0, 10)
and
backflips = math.clamp(backflips - 1, 0, 10)
then when I do 2 frontflips
the result tells me
I have performed 2 frontflips and 1 backflip.

Issue with a Lua Script

i really hope im right here, as on a discord server no one wants to help me for some reason.
We run a Project for a game called Garry's Mod and currently try to get a "Toxic Gas" Script Working.
But we face the following issue
[ERROR] gamemodes/zombierp/plugins/toxicgas/sh_plugin.lua:44: attempt to index local 'item' (a boolean value)
1. IsEquippingGasmask - gamemodes/zombierp/plugins/toxicgas/sh_plugin.lua:44
2. v - gamemodes/zombierp/plugins/toxicgas/sh_plugin.lua:121
3. unknown - gamemodes/helix/gamemode/core/libs/sh_plugin.lua:477
And me being fairly new to Lua, im just completly confused and dont know how to fix it.
Here is the Full Script
local config = {
smokeColor = Color(63, 127, 0),
smokeAlpha = 110,
maskItem = "gasmask",
smokeSpawnerDistance = 100 -- distance between the smoke emitters on the box line
}
local PLUGIN = PLUGIN
PLUGIN.name = "Toxic Gas"
PLUGIN.author = ""
PLUGIN.description = ""
PLUGIN.positions = PLUGIN.positions or {}
PLUGIN.smokeStacks = PLUGIN.smokeStacks or {}
function PLUGIN:LoadData()
PLUGIN.positions = self:GetData()
self:UpdateWorldData()
end
function PLUGIN:SaveData()
self:SetData(PLUGIN.positions)
self:UpdateWorldData()
end
function PLUGIN:UpdateWorldData()
SetNetVar("toxicGasPositions", PLUGIN.positions)
-- global netvar doesn't seem to sync without this
for _, ply in pairs(player.GetAll()) do
ply:SyncVars()
end
end
function PLUGIN:IsEquippingGasmask(ply)
local character = ply:GetCharacter()
if not character then return false end
local inventoryID = character:GetInventory():GetID()
local inventory = ix.item.inventories[inventoryID]
for x, items in pairs(inventory.slots) do
for y, item in pairs(items) do
if item.uniqueID == config.maskItem
and item:GetData("equip") == true then
return true
end
end
end
return false
end
local function GetBoxLine(min, max)
local deltaX = math.abs(min.x - max.x)
local deltaY = math.abs(min.y - max.y)
local lineStart, lineEnd
if deltaX < deltaY then
lineStart = Vector(min.x + (max.x - min.x) / 2, min.y, min.z)
lineEnd = Vector(min.x + (max.x - min.x) / 2, min.y + (max.y - min.y), min.z)
else
lineStart = Vector(min.x, min.y + (max.y - min.y) / 2, min.z)
lineEnd = Vector(min.x + (max.x - min.x), min.y + (max.y - min.y) / 2, min.z)
end
return lineStart, lineEnd
end
if SERVER then
function PLUGIN:Think()
for idx, gasBox in pairs(PLUGIN.positions) do
if PLUGIN.smokeStacks[idx] == nil then
local min, max = gasBox.min, gasBox.max
local startSmoke, endSmoke = GetBoxLine(min, max)
PLUGIN.smokeStacks[idx] = {
count = math.floor(startSmoke:Distance(endSmoke) / config.smokeSpawnerDistance),
stacks = {}
}
for i = 1, PLUGIN.smokeStacks[idx].count do
local smoke = ents.Create("env_smokestack")
smoke:SetPos(startSmoke + (endSmoke - startSmoke):GetNormalized() * (i) * config.smokeSpawnerDistance)
smoke:SetKeyValue("InitialState", "1")
smoke:SetKeyValue("WindAngle", "0 0 0")
smoke:SetKeyValue("WindSpeed", "0")
smoke:SetKeyValue("rendercolor", tostring(config.smokeColor))
smoke:SetKeyValue("renderamt", tostring(config.smokeAlpha))
smoke:SetKeyValue("SmokeMaterial", "particle/particle_smokegrenade.vmt")
smoke:SetKeyValue("BaseSpread", tostring(config.smokeSpawnerDistance))
smoke:SetKeyValue("SpreadSpeed", "10")
smoke:SetKeyValue("Speed", "32")
smoke:SetKeyValue("StartSize", "32")
smoke:SetKeyValue("EndSize", "32")
smoke:SetKeyValue("roll", "8")
smoke:SetKeyValue("Rate", "64")
smoke:SetKeyValue("JetLength", tostring(max.z - min.z))
smoke:SetKeyValue("twist", "6")
smoke:Spawn()
smoke:Activate()
smoke.Think = function()
if PLUGIN.positions[idx] == nil then
smoke:Remove()
end
end
PLUGIN.smokeStacks[idx].stacks[i] = smoke
end
end
end
for _, ply in pairs(player.GetAll()) do
local pos = ply:EyePos()
if not ply:Alive() then continue end
local canBreathe = false
if not canBreathe then
canBreathe = self:IsEquippingGasmask(ply)
end
if not canBreathe then
for _, gasBox in pairs(PLUGIN.positions) do
if pos:WithinAABox(gasBox.min, gasBox.max) then
ply.nextGasDamage = ply.nextGasDamage or CurTime()
if CurTime() >= ply.nextGasDamage then
ply.nextGasDamage = CurTime() + .75
ply:TakeDamage(6)
ix.util.Notify("You are choking. You need a gas mask.", ply)
end
break
end
end
end
end
end
end
if CLIENT then
-- toggles showing toxic gas boxes when in noclip/observer
CreateConVar("ix_toxicgas_observer", "0", FCVAR_ARCHIVE)
local function IsInRange(min, max, scale)
local localPos = LocalPlayer():GetPos()
local distance = min:Distance(max)
if localPos:Distance(min + ((max - min) / 2)) <= distance * scale then
return true
end
return false
end
function PLUGIN:PostDrawTranslucentRenderables()
local toxicGasPositions = GetNetVar("toxicGasPositions")
if toxicGasPositions == nil then return end
for _, gasBox in pairs(toxicGasPositions) do
local min, max = gasBox.min, gasBox.max
if not IsInRange(min, max, 3) then continue end
local observerCvar = GetConVar("ix_toxicgas_observer")
if LocalPlayer():IsAdmin()
and LocalPlayer():GetMoveType() == MOVETYPE_NOCLIP
and observerCvar and observerCvar:GetBool() then
render.DrawWireframeBox(min, Angle(), Vector(0, 0, 0), max - min, Color(142, 222, 131, 255), false)
local startSmoke, endSmoke = GetBoxLine(min, max)
render.DrawLine(startSmoke, endSmoke, Color(0, 255, 0), false)
end
end
end
function PLUGIN:HUDPaint()
-- this is an FPS killer tbh
--[[
local toxicGasPositions = game.GetWorld():GetNetVar("toxicGasPositions")
if toxicGasPositions == nil then return end
local inToxicGas = false
local center
local cornerDist
for _, gasBox in pairs(toxicGasPositions) do
local min, max = gasBox.min, gasBox.max
center = min + ((max - min) / 2)
cornerDist = min:Distance(max)
if LocalPlayer():EyePos():WithinAABox(min, max) then
inToxicGas = true
continue
end
end
if inToxicGas then
local isEquippingGasmask = self:IsEquippingGasmask(LocalPlayer())
local distance = LocalPlayer():EyePos():Distance(center)
ix.util.DrawBlurAt(0, 0, ScrW(), ScrH(), 1, 0.2, isEquippingGasmask and 50 or 255)
end
]]
end
end
ix.command.Add("AddToxicGas", {
description = "Adds a toxic gas box from where you're standing and where you're looking at.",
adminOnly = true,
OnRun = function(self, client)
local pos = client:GetPos()
local tr = client:GetEyeTrace()
if not tr then return end
local hitPos = tr.HitPos
table.insert(PLUGIN.positions, {
min = pos, max = hitPos
})
PLUGIN:SaveData()
return "Added toxic gas."
end
})
ix.command.Add("RemoveToxicGas", {
description = "Removes the closest toxic gas point relative to you.",
adminOnly = true,
OnRun = function(self, client)
local closestDistance = -1
local closestIndex = -1
for idx, gasBox in pairs(PLUGIN.positions) do
local min, max = gasBox.min, gasBox.max
local center = min + ((max - min) / 2)
local distance = client:GetPos():Distance(center)
if closestDistance == -1 or distance < closestDistance then
closestDistance = distance
closestIndex = idx
end
end
if closestIndex ~= -1 then
table.remove(PLUGIN.positions, closestIndex)
if PLUGIN.smokeStacks[closestIndex] then
for k, v in pairs(PLUGIN.smokeStacks[closestIndex].stacks) do
v:Remove()
end
table.remove(PLUGIN.smokeStacks, closestIndex)
end
PLUGIN:SaveData()
return "Removed 1 toxic gas box."
else
return "Could not find any toxic gas to remove!"
end
end
})
I Really hope someone can help me with that as im trying since 2 days now
Try replacing for y, item in pairs(items) do with for item, _ in pairs(items) do.
Reason: there is a chance that items is a set, i.e., a Lua table, in which keys are set members and values are true.
change line 44
if item.uniqueID == config.maskItem
either by refusing boolean values
if type(item) ~= 'boolean' and item.uniqueID == config.maskItem
or only allowing tables, because they could possibly contain .uniqueID
if type(item) == 'table' and item.uniqueID == config.maskItem

How can I change the ball's colour in pong when it collides with a paddle in Lua using Love2D

So, I am trying to make a game that replicates pong, and I am currently stuck on one piece. I want it so that when the ball collides with either paddle, then it will change colour. Except it doesn't do as I say. It would be much appreciated if anyone can give a tip as to fixing this issue I am currently having, anyways, here is the code. I am only giving the main file and ball class, as those are the only relevant item I think you will need. This is written in Lua with the help of Love2D. This is an old version of Love2D, to be exact 0.10.2
main.lua:
push = require 'push'
Class = require 'class'
require 'Paddle'
require 'Ball'
windowWidth = 1280
windowHeight = 720
virtualWidth = 432
virtualHeight = 243
paddleSpeed = 200
-- Boolean values that can be changed if we want a paddle to become an AI
AIMode = false -- left paddle AI
AIMode_2 = false -- right paddle AI
AISpeed = 0
function love.load()
love.graphics.setDefaultFilter('nearest', 'nearest')
love.window.setTitle('Pong')
math.randomseed(os.time())
smallFont = love.graphics.newFont('font.ttf', 8)
largeFont = love.graphics.newFont('font.ttf', 16)
scoreFont = love.graphics.newFont('font.ttf', 32)
sounds = {
['paddle_hit'] = love.audio.newSource('sounds/paddle_hit.wav', 'static'),
['score'] = love.audio.newSource('sounds/score.wav', 'static'),
['wall_hit'] = love.audio.newSource('sounds/wall_hit.wav', 'static')
}
love.graphics.setFont(smallFont)
push:setupScreen(virtualWidth, virtualHeight, windowWidth, windowHeight, {
fullscreen = false,
resizable = false,
vsync = true
})
p1_score = 0
p2_score = 0
servingPlayer = 1
winningPlayer = 0
player_1 = Paddle(10, 30, 5, 20)
player_2 = Paddle(virtualWidth - 10, virtualHeight - 30, 5, 20)
ball = Ball(virtualWidth / 2 - 2, virtualHeight / 2 - 2, 4, 4)
gameState = 'start'
end
function love.update(dt)
if gameState == 'serve' then
ball.dy = math.random(-50, 50)
if servingPlayer == 1 then
ball.dx = math.random(140, 200)
else
ball.dx = -math.random(140, 200)
end
elseif gameState == 'play' then
if ball:collides(player_1) then
ball.dx = -ball.dx * 1.03
ball.x = player_1.x + 5
if ball.dy < 0 then
ball.dy = -math.random(10, 150)
else
ball.dy = math.random(10, 150)
end
sounds['paddle_hit']:play()
end
if ball:collides(player_2) then
ball.dx = -ball.dx * 1.03
ball.x = player_2.x - 4
if ball.dy < 0 then
ball.dy = -math.random(10, 150)
else
ball.dy = math.random(10, 150)
end
sounds['paddle_hit']:play()
end
if ball.y <= 0 then
ball.y = 0
ball.dy = -ball.dy
sounds['wall_hit']:play()
end
if ball.y >= virtualHeight - 4 then
ball.y = virtualHeight - 4
ball.dy = -ball.dy
sounds['wall_hit']:play()
end
end
if ball.x < 0 then
ball:reset()
gameState = 'serve'
servingPlayer = 1
p2_score = p2_score + 1
sounds['score']:play()
end
if p2_score == 10 then
winningPlayer = 2
gameState = 'done'
end
if ball.x > virtualWidth then
ball:reset()
gameState = 'serve'
servingPlayer = 2
p1_score = p1_score + 1
sounds['score']:play()
end
if p1_score == 10 then
winningPlayer = 1
gameState = 'done'
end
if AIMode == true and AIMode_2 == true then
if p1_score == 3 then
winningPlayer = 1
gameState = 'done'
elseif p2_score == 3 then
winningPlayer = 2
gameState = 'done'
end
end
-- For Single Player Mode
-- If only the left paddle is AI, then left paddle's Y position will be the same as the ball's Y position. Only the right will be controlled by the player by pressing keys 'up', and 'down'
if AIMode == true and AIMode_2 == false then
player_1.y = ball.y
if love.keyboard.isDown('up') then
player_2.dy = -paddleSpeed
elseif love.keyboard.isDown('down') then
player_2.dy = paddleSpeed
else
player_2.dy = 0
end
end
-- For Auto Mode
-- If both paddles are AI, then both paddle's y position will be the same as the ball's y postion
if AIMode == true and AIMode_2 == true then
player_1.y = ball.y
player_2.y = ball.y
end
-- For 2 Player Mode
-- If no paddles are AI, then left paddle will be controlled by pressing 'w' and 's', and the right paddle will be controlled by pressing 'up' and 'down'
if AIMode == false and AIMode_2 == false then
if love.keyboard.isDown('w') then
player_1.dy = -paddleSpeed
elseif love.keyboard.isDown('s')then
player_1.dy = paddleSpeed
else
player_1.dy = 0
end
if love.keyboard.isDown('up') then
player_2.dy = -paddleSpeed
elseif love.keyboard.isDown('down') then
player_2.dy = paddleSpeed
else
player_2.dy = 0
end
end
if gameState == 'play' then
ball:update(dt)
end
player_1:update(dt)
player_2:update(dt)
end
function love.keypressed(key)
-- if key '1' is pressed in start screen, then left paddle will become AI
-- Single Player Mode
if key == '1' and gameState == 'start' then
AIMode = true
AIMode_2 = false
-- if key '2' is pressed in start screen, then both paddles will become AI
-- Auto Mode
elseif key == '2' and gameState == 'start' then
AIMode_2 = true
AIMode = true
-- if key '3' is pressed, then no paddles will become AI
-- 2 Player Mode
elseif key == '3' and gameState == 'start' then
AIMode = false
AIMode_2 = false
end
if key == 'escape' then
love.event.quit()
elseif key == 'enter' or key == 'return' then
if gameState == 'start' then
gameState = 'serve'
elseif gameState == 'serve' then
gameState = 'play'
elseif gameState == 'done' then
ball:reset()
p1_score = 0
p2_score = 0
if winningPlayer == 1 then
servingPlayer = 2
else
servingPlayer = 1
end
if key == 'enter' or key == 'return' then
gameState = 'serve'
end
-- if playing and enter is pressed, then ball will reset, and player will be brought back to the start screen
-- soft reset
elseif gameState == 'play' then
gameState = 'start'
ball:reset()
end
end
-- if 'r' is pressed in any state, then all score will reset, as well as the entire game, and player will be brought back to the start screen
-- hard reset
if key == 'r' then
if gameState == 'start' or gameState == 'serve' or gameState == 'play' or gameState == 'done' then
gameState = 'start'
p1_score = 0
p2_score = 0
ball:reset()
end
end
end
function love.draw()
push:apply('start')
love.graphics.clear(40, 45, 52, 255)
love.graphics.setFont(smallFont)
displayScore()
if gameState == 'start' then
love.graphics.setFont(smallFont)
if AIMode == true and AIMode_2 == false then
love.graphics.printf('AI Mode ON! Computer vs. Player!', 0, 30, virtualWidth, 'center')
elseif AIMode_2 == true and AIMode == true then
love.graphics.printf('AI Mode ON! Computer vs. Computer!', 0, 30, virtualWidth, 'center')
elseif AIMode == false and AIMode_2 == false then
love.graphics.printf('AI Mode OFF! 2 Player Mode!', 0, 30, virtualWidth, 'center')
end
love.graphics.printf('Welcome to Pong', 0, 10, virtualWidth, 'center')
love.graphics.printf('Press Enter to Begin! Press 1 for Single Player Mode, 2 for Automatic Mode, 3 for 2 Player Mode!', 0, 20, virtualWidth, 'center')
elseif gameState == 'serve' then
if AIMode == false and AIMode_2 == false then
love.graphics.setFont(smallFont)
love.graphics.printf('Player ' .. tostring(servingPlayer) .. "'s serve!", 0, 10, virtualWidth, 'center')
love.graphics.printf('Press Enter to Serve!', 0, 20, virtualWidth, 'center')
elseif AIMode == true and AIMode_2 == false then
if servingPlayer == 1 then
love.graphics.setFont(smallFont)
love.graphics.printf('Computer Serve!', 0, 10, virtualWidth, 'center')
love.graphics.printf('Press Enter to Serve!', 0, 20, virtualWidth, 'center')
else
love.graphics.setFont(smallFont)
love.graphics.printf('Player Serve!', 0, 10, virtualWidth, 'center')
love.graphics.printf('Press Enter to Serve!', 0, 20, virtualWidth, 'center')
end
elseif AIMode == true and AIMode_2 == true then
love.graphics.setFont(smallFont)
love.graphics.printf('Computer ' .. tostring(servingPlayer) .. "'s serve!", 0, 10, virtualWidth, 'center')
love.graphics.printf('Press Enter to Serve!', 0, 20, virtualWidth, 'center')
end
elseif gameState == 'play' then
elseif gameState == 'done' then
if AIMode == false and AIMode_2 == false then
love.graphics.setFont(largeFont)
love.graphics.printf('Player ' .. tostring(winningPlayer) .. ' wins!', 0, 10, virtualWidth, 'center')
love.graphics.setFont(smallFont)
love.graphics.printf('Press Enter to Restart!', 0, 30, virtualWidth, 'center')
elseif AIMode == true and AIMode_2 == false then
if winningPlayer == 1 then
love.graphics.setFont(largeFont)
love.graphics.printf('Computer Wins!', 0, 10, virtualWidth, 'center')
love.graphics.setFont(smallFont)
love.graphics.printf('Press Enter to Restart!', 0, 30, virtualWidth, 'center')
else
love.graphics.setFont(largeFont)
love.graphics.printf('Player Wins!', 0, 10, virtualWidth, 'center')
love.graphics.setFont(smallFont)
love.graphics.printf('Press Enter to Restart!', 0, 30, virtualWidth, 'center')
end
elseif AIMode == true and AIMode_2 == true then
love.graphics.setFont(largeFont)
love.graphics.printf('Computer ' .. tostring(winningPlayer) .. ' wins!', 0, 10, virtualWidth, 'center')
love.graphics.setFont(smallFont)
love.graphics.printf('Press Enter to Restart!', 0, 30, virtualWidth, 'center')
end
end
love.graphics.setColor(255, 0, 0, 255)
player_1:render()
love.graphics.setColor(255, 255, 0, 255)
player_2:render()
love.graphics.setColor(255, 255, 255, 255)
-- this is where I am having the issue
if ball:collides(player_1) then
love.graphics.setColor(255, 0, 0, 255)
elseif ball:collides(player_2) then
love.graphics.setColor(255, 255, 0, 255)
end
ball:render()
displayFPS()
push:apply('end')
end
function displayFPS()
love.graphics.setFont(smallFont)
love.graphics.setColor(0, 255, 0, 255)
love.graphics.print('FPS: ' .. tostring(love.timer.getFPS()), 10, 10)
end
function displayScore()
love.graphics.setFont(scoreFont)
love.graphics.setColor(255, 0, 0, 255)
love.graphics.print(tostring(p1_score), virtualWidth / 2 - 50,
virtualHeight / 3)
love.graphics.setColor(255, 255, 0, 255)
love.graphics.print(tostring(p2_score), virtualWidth / 2 + 30,
virtualHeight / 3)
love.graphics.setColor(255, 255, 255, 255)
end
Ball.lua:
Ball = Class{}
function Ball:init(x, y, width, height)
self.x = x
self.y = y
self.width = width
self.height = height
self.dy = math.random(2) == 1 and -100 or 100
self.dx = math.random(2) == 1 and math.random(-80, -100) or math.random(80, 100)
end
function Ball:collides(paddle)
if self.x > paddle.x + paddle.width or paddle.x > self.x + self.width then
return false
end
if self.y > paddle.y + paddle.height or paddle.y > self.y + self.height then
return false
end
love.graphics.setColor(math.random(0, 255), math.random(0, 255), math.random(0, 255), 255)
return true
end
function Ball:reset()
self.x = virtualWidth / 2 - 2
self.y = virtualHeight / 2 - 2
self.dy = math.random(2) == 1 and -100 or 100
self.dx = math.random(-50, 50)
end
function Ball:update(dt)
self.x = self.x + self.dx * dt
self.y = self.y + self.dy * dt
end
function Ball:render()
love.graphics.rectangle('fill', self.x, self.y, self.width, self.height)
end
Paddle.lua
Paddle = Class{}
function Paddle:init(x, y, width, height)
self.x = x
self.y = y
self.width = width
self.height = height
self.dy = 0
end
function Paddle:update(dt)
if self.dy < 0 then
self.y = math.max(0, self.y + self.dy * dt)
else
self.y = math.min(virtualHeight - self.height, self.y + self.dy * dt)
end
end
function Paddle:render()
love.graphics.rectangle('fill', self.x, self.y, self.width, self.height)
end
nevermind I did some stuff, and made a new variable called ballCollDetect, where the default value is 0. If it hits the left paddle, then it turns into 1, and if it hits right paddle, then it turns into 2. So, if it = 1, then the ball's colour will be red, and if it = 2, then the ball's colour will be yellow, and the default value will just make the ball's colour white. Pretty simple actually.

SprintingAnimation:19: Expected ')' (to close '(' at column 29), got ','

In my game I've made a feature where you can sprint.
I've separated the animation part of the script from the main sprinting part.
I got the error message "Workspace.Vlo_tz.SprintingAnimation:19: Expected ')' (to close '(' at column 29), got ','".
This code is for the animation of the character and the sprinting bar
local UIS = game:GetService('UserInputService')
local Player = game.Players.LocalPlayer
local Character = Player.Character
local players = game:GetService("Players")
local stamina = players.LocalPlayer.PlayerGui.StaminaHealth.MainFrame.Stamina
UIS.InputBegan:connect(function(input)
local humanoid = Player.Character.Humanoid
if input.KeyCode == Enum.KeyCode.LeftShift and humanoid:GetState() == Enum.HumanoidStateType.RunningNoPhysics and humanoid.MoveDirection.Magnitude > 0 then
local Anim = Instance.new('Animation')
Anim.AnimationId = 'rbxassetid://05168161960'
PlayAnim = Character.Humanoid:LoadAnimation(Anim)
PlayAnim:Play()
while true do
wait(0.05)
if stamina.Position <= (-0.343, 0, 0.274, 0) then
stamina.Position = UDim2.new(-0.343, 0, 0, 0)
else
stamina.Position = stamina.Position - UDim2.new(0.01, 0, 0, 0)
end
end
end
end)
UIS.InputEnded:connect(function(input)
if input.KeyCode == Enum.KeyCode.LeftShift then
PlayAnim:Stop()
while true do
wait(0.005)
if stamina.Position >= (0.487, 0, 0.274, 0) then
stamina.Position = UDim2.new(0.487, 0, 0, 0)
else
stamina.Position = stamina.Position + UDim2.new(0.01, 0, 0, 0)
end
end
end
end)
local humanoid = Player.Character.Humanoid
if humanoid.MoveDirection.Magnitude == 0 then
PlayAnim:Stop()
while true do
wait(0.005)
if stamina.Position >= (0.487, 0, 0.274, 0) then
stamina.Position = UDim2.new(0.487, 0, 0, 0)
else
stamina.Position = stamina.Position + UDim2.new(0.01, 0, 0, 0)
end
end
end
Line 19 is this : if stamina.Position <= (-0.343, 0, 0.274, 0) then
You have this check in a few different places, but this is not valid lua and you cannot compare UDim2 values like this. You'll have to inspect the values individually.
local isLessThanX = stamina.Position.X.Scale <= -0.343
local isLessThanY = stamina.Position.Y.Scale <= 0.274
if isLessThanX and isLessThanY then

how do I fix my script made in Roblox Lua?

I'm making my script and the Script Analysis tool says
Error: (54,2) Expected , got 'end'
I thought maybe you guys might help.
Here is the code
-- to be placed in StarterPlayer > StarterPlayerScripts
local Players = game:GetService("Players")
-- wait for local player PlayerGui
local LocalPlayer = Players.LocalPlayer
local playerGui = LocalPlayer:WaitForChild("PlayerGui")
-- create a ScreenGui
local screenGui = Instance.new("ScreenGui", playerGui)
-- create a holder for our bar
local frame = Instance.new("Frame", screenGui)
frame.AnchorPoint = Vector2.new(0.0, 0.0)
frame.Position = UDim2.new(0.0, 0, 0.0, 0)
frame.Size = UDim2.new(0.0, 0, 0.0, 0)
-- create a bar
local bar = Instance.new("Frame", frame)
bar.Position = UDim2.new(0, 0, 0, 0)
bar.Size = UDim2.new(1, 0, 1, 0)
bar.BackgroundColor3 = Color3.new(0, 1, 0)
-- create a sound
local sound = Instance.new("Sound", screenGui)
local lastLoudness = 0
sound.SoundId = "rbxassetid://697821987"
sound.Looped = true
sound:Play()
-- define a max loudness
local maxLoudness = 30
-- animate the amplitude bar
while true do
local amplitude = math.clamp(sound.PlaybackLoudness / maxLoudness, 0, 1)
print(80-(game.Workspace.CurrentCamera.FieldOfView))
bar.Size = UDim2.new(sound.PlaybackLoudness / maxLoudness, 0, 0, 0)
wait(0.00001)
local lastLoudness = 0
local PBS = ((sound.PlaybackLoudness/50)^(sound.PlaybackLoudness/50))
if lastLoudness~=0 then
local formula = math.abs((lastLoudness*15)) + ((lastLoudness+PBS)/1.9)
if (math.abs(PBS) > formula) == true then
game.Workspace.CurrentCamera.FieldOfView = (lastLoudness)
if game.Workspace.CurrentCamera.FieldOfView <= 10 then
print(formula, PBS)
else
game.Workspace.CurrentCamera.FieldOfView = 0
print(formula, PBS)
end
end
end
end
end
end
I genuinely Don't know how to fix the code, So...
Could you guys Help me?
I spent a long time (a couple of hours) on this and I'm legitimately stuck in the deepest pits of coding hell. And I want this fixed SO BADLY.
Also, Just To Clarify, The script is supposed to change FOV when sound.PlaybackLoudness ÷ 50 × sound.PlaybackLoudness ÷ 50 is over 0.
Egor Skriptunoff is right. Let me reformat your while-loop to show you why.
-- animate the amplitude bar
while true do
local amplitude = math.clamp(sound.PlaybackLoudness / maxLoudness, 0, 1)
print(80-(game.Workspace.CurrentCamera.FieldOfView))
bar.Size = UDim2.new(sound.PlaybackLoudness / maxLoudness, 0, 0, 0)
wait(0.00001)
local lastLoudness = 0
local PBS = ((sound.PlaybackLoudness/50)^(sound.PlaybackLoudness/50))
if lastLoudness~=0 then
local formula = math.abs((lastLoudness*15)) + ((lastLoudness+PBS)/1.9)
if (math.abs(PBS) > formula) == true then
game.Workspace.CurrentCamera.FieldOfView = (lastLoudness)
if game.Workspace.CurrentCamera.FieldOfView <= 10 then
print(formula, PBS)
else
game.Workspace.CurrentCamera.FieldOfView = 0
print(formula, PBS)
end
end
end
end
end -- <-- these bad boys don't go with anything
end -- <-- just remove them to get rid of the error
EDIT : Here's a more complete answer to help with your other script issues. You were resizing your animation stuff to 0 pixels tall, so you couldn't see anything.
-- to be placed in StarterPlayer > StarterPlayerScripts
local Players = game:GetService("Players")
-- wait for local player PlayerGui
local LocalPlayer = Players.LocalPlayer
local playerGui = LocalPlayer:WaitForChild("PlayerGui")
-- create a ScreenGui
local screenGui = Instance.new("ScreenGui", playerGui)
-- create a holder for our bar
local frame = Instance.new("Frame", screenGui)
frame.AnchorPoint = Vector2.new(0.0, 0.0)
frame.Position = UDim2.new(0.0, 0, 0.0, 0)
frame.Size = UDim2.new(1.0, 0, 0.0, 50) -- <-- this is no longer invisible
-- create a bar
local bar = Instance.new("Frame", frame)
bar.Position = UDim2.new(0, 0, 0, 0)
bar.Size = UDim2.new(1, 0, 1, 0)
bar.BackgroundColor3 = Color3.new(0, 1, 0)
-- create a sound
local sound = Instance.new("Sound", screenGui)
local lastLoudness = 0
sound.SoundId = "rbxassetid://697821987"
sound.Looped = true
sound:Play()
-- define a max loudness
local maxLoudness = 30.0 -- <-- this needed to be a decimal value
local lastLoudness = 0
-- animate the amplitude bar
while true do
-- PlaybackLoudness values range from 0 to 500, so downscale it
local sampledLoundness = (sound.PlaybackLoudness / 50)
local amplitude = math.clamp(sampledLoundness / maxLoudness, 0, 1)
print("sound values : ", sound.PlaybackLoudness, maxLoudness, amplitude)
-- animate the bar
bar.Size = UDim2.new(amplitude, 0, 1, 0) -- <-- this was squashed to 0 pixels
wait(0.00001)
-- create a camera shake effect
-- NOTE - not sure what the expected behavior is here, it just zooms in
local PBS = sampledLoundness ^ sampledLoundness
if lastLoudness ~=0 then
local formula = math.abs(lastLoudness * 15) + ((lastLoudness + PBS) / 1.9)
if (math.abs(PBS) > formula) == true then
game.Workspace.CurrentCamera.FieldOfView = lastLoudness
if game.Workspace.CurrentCamera.FieldOfView <= 10 then
print("FOV is less than 10 : ", formula, PBS)
else
game.Workspace.CurrentCamera.FieldOfView = 0
print("FOV forced to 0 : ", formula, PBS)
end
end
end
-- update lastLoudness and loop
lastLoudness = sampledLoundness
end

Resources