Cannot change the boolean in table lua love2d - lua

I am creating a simple platformer with love2d in lua.
I want the player to stand on the ground so that it won't fall.
However I got some proablem that I cannot change the string of a table return from player.lua
(It is a table because the player.lua return m and the last sentance, and m is a table)
I tested that the isOnFloor function is work, but I just can't change the boolean in the player table.
Main.lua
local love = require("love")
local tileMapper = require("tile/tileMapper")
local player = require "player"
local isOnFloor = require("isOnFloor")
function love.load()
love.window.setMode(1080, 640)
love.window.setTitle("Simple Platformer")
tileMapper:spawn()
tiles = tileMapper.tiles
player:setValue()
love.keyboard.keyPressed = {}
end
function love.update(dt)
for i = 1, #tiles do
if isOnFloor(player.x, player.y, tiles[i].x, tiles[i].y, 32, 32 * 3, 72, 72) then
player.currentState = "ground" -- I wanna change it here but when I go back to
--player.lua and try to let it out put the self.currentState, nothing changed --
else
player.currentState = "air"
end
end
player:update(dt)
love.keyboard.keyPressed = {}
end
I try to print out the player.currentState the the line after I set the player.currentState = "ground". It printed out "ground"
But if I print it in player.lua, it is always "air"
player.lua(I didn't paste some of the code here)
m = {}
function m:setValue()
self.x = 400
self.y = 50
self.vtx = 0
self.y_input = 0
self.speed = 300
self.jumpForce = -800
self.gravity = 100
self.anim = {idle = {img = love.graphics.newImage("assets/Idle.png"), maxFrame = 10},
run = {img = love.graphics.newImage("assets/Run.png"), maxFrame = 11},
jump = {img = love.graphics.newImage("assets/Jump.png"), maxFrame = 0},
fall = {img = love.graphics.newImage("assets/Fall.png"), maxFrame = 0}}
self.currentAnim = nil
for i = 1, #self.anim do
self.anim[i]:setFilter("nearest", "nearest")
end
self.frame = 0
self.timer = 0
self.currentState = nil
end
function m:update(dt)
print(self.currentState)
---------------------- Player States Update ------------------------
self:getXInput()
if self.currentState == "ground" then
if self.vtx == 0 then
self.currentAnim = self.anim.idle
elseif not(self.vtx == 0) then
self.currentAnim = self.anim.run
end
elseif self.currentState == "air" then
self.y_input = self.y_input + self.gravity
if self.y_input > 0 then
self.currentAnim = self.anim.fall
elseif self.y_input < 0 then
self.currentAnim = self.anim.jump
end
end
------------------------ Anim --------------------
self:animUpdate(dt)
if love.keyboard.keyPressed["space"] == true then
self.y_input = self.jumpForce
end
self.x = self.x + self.speed * dt * self.vtx
self.y = self.y + self.y_input * dt
end
return m
If you have an idea of this porblem, please tell, thank you.

Related

Why does unequipping this tool relocates the player to the center of the map in Roblox?

This gear was inserted from the Catalog. It relocates the player to the center of the map when it's unequipped by clicking on the thumbnail. At 1st, I tested in a game I made. Everytime I unequipped it, the player kept falling through the baseplate and dying. I noticed it is the same position over and over. I moved the baseplate's position lower and the player falls down onto the baseplate instead of dying. Then I tested the gear in a new empty baseplate, unequipping it, the player moves to the center, too. I check the position of the both the Handle and the player's Torso, but that axis does not match any position in the script. Can someone point this out for me so that I can change it to the last position that the player stops?
Tool = script.Parent
Handle = Tool:WaitForChild("Handle")
Players = game:GetService("Players")
Debris = game:GetService("Debris")
Assets = require(Tool:WaitForChild("Assets"))
Data = Assets.Data
BaseUrl = Assets.BaseUrl
BasePart = Instance.new("Part")
BasePart.Material = Enum.Material.Plastic
BasePart.Shape = Enum.PartType.Block
BasePart.TopSurface = Enum.SurfaceType.Smooth
BasePart.BottomSurface = Enum.SurfaceType.Smooth
BasePart.FormFactor = Enum.FormFactor.Custom
BasePart.Size = Vector3.new(0.2, 0.2, 0.2)
BasePart.Anchored = false
BasePart.CanCollide = true
BasePart.Locked = true
Animations = {
Hold = {Animation = Tool:WaitForChild("Hold"), FadeTime = nil, Weight = nil, Speed = nil}
}
Sounds = {
Honk = Handle:WaitForChild("Honk"),
Engine = Handle:WaitForChild("Running")
}
Controls = {
Forward = {Key = "w", ByteKey = 17, Mode = false},
Backward = {Key = "s", ByteKey = 18, Mode = false},
Left = {Key = "a", ByteKey = 20, Mode = false},
Right = {Key = "d", ByteKey = 19, Mode = false}
}
Rate = (1 / 60)
Gravity = 196.20
PoseOffset = CFrame.new(0, -1.5125, -0.3) * CFrame.Angles(0, 0, 0) --The offset your character is from the center of the vehicle.
SpeedBoost = {
Allowed = false,
Active = false,
Enabled = true,
Duration = 10,
ReloadTime = 30
}
Special = {
Allowed = false,
Enabled = true,
Active = false,
Duration = 0,
ReloadTime = 60
}
Speed = {
Acceleration = {
Normal = 30,
Boost = 30
},
Deceleration = {
Normal = 30,
Boost = 30
},
MovementSpeed = {
Normal = {Min = 20, Max = 70},
Boost = {Min = 20, Max = 70}
},
TurnSpeed = {
Speed = {Min = 5, Max = 5},
TurnAlpha = 0.30,
AlphaDampening = 0.2
},
}
MaxSpeed = { --Maximum speed which the vehicle can move and turn at.
Movement = Speed.MovementSpeed.Normal,
Turn = Speed.TurnSpeed.Speed,
Acceleration = Speed.Acceleration.Normal,
Deceleration = Speed.Deceleration.Normal
}
CurrentSpeed = { --The speed which the vehicle is moving and turning at.
Movement = 0,
Turn = 0
}
Honk = {
Honking = false,
LastHonk = 0,
ReloadTime = 1
}
Jump = {
Jumping = false,
LastJump = 0,
ReloadTime = 1.25,
JumpForce = 30
}
ToolEquipped = false
ServerControl = (Tool:FindFirstChild("ServerControl") or Instance.new("RemoteFunction"))
ServerControl.Name = "ServerControl"
ServerControl.Parent = Tool
ClientControl = (Tool:FindFirstChild("ClientControl") or Instance.new("RemoteFunction"))
ClientControl.Name = "ClientControl"
ClientControl.Parent = Tool
Tool.Enabled = true
function RayCast(Position, Direction, MaxDistance, IgnoreList)
local IgnoreList = ((type(IgnoreList) == "table" and IgnoreList) or {IgnoreList})
return game:GetService("Workspace"):FindPartOnRayWithIgnoreList(Ray.new(Position, Direction.unit * (MaxDistance or 999.999)), IgnoreList)
end
function GetAllConnectedParts(Object)
local Parts = {}
local function GetConnectedParts(Object)
for i, v in pairs(Object:GetConnectedParts()) do
local Ignore = false
for ii, vv in pairs(Parts) do
if v == vv then
Ignore = true
end
end
if not Ignore then
table.insert(Parts, v)
GetConnectedParts(v)
end
end
end
GetConnectedParts(Object)
return Parts
end
function EnableFirstPersonView()
if not CheckIfAlive() or not ToolEquipped then
return
end
local Limbs = {"LeftHand", "RightHand"}
for i, v in pairs(Limbs) do
local Limb = Character:FindFirstChild(v)
if Limb:IsA("BasePart") then
Spawn(function()
InvokeClient("SetLocalTransparencyModifier", {Object = Limb, Transparency = 0, AutoUpdate = false})
end)
end
end
end
function ThrustUpdater()
for i, v in pairs(CurrentSpeed) do
CurrentSpeed[i] = 0
end
for i, v in pairs(Controls) do
Controls[i].Mode = false
end
while ToolEquipped and Body and Body.Parent and CheckIfAlive() and RotationForce and RotationForce.Parent and ThrustForce and ThrustForce.Parent and TurnGyro and TurnGyro.Parent do
RotationForce.angularvelocity = Vector3.new(0, CurrentSpeed.Turn, 0)
if math.abs(CurrentSpeed.Turn) > Speed.TurnSpeed.AlphaDampening then
CurrentSpeed.Turn = (CurrentSpeed.Turn - (Speed.TurnSpeed.AlphaDampening * (math.abs(CurrentSpeed.Turn) / CurrentSpeed.Turn)))
else
CurrentSpeed.Turn = 0
end
if not Controls.Forward.Mode or Controls.Backward.Mode then --Slow down if not controlling.
CurrentSpeed.Movement = (CurrentSpeed.Movement * 0.99)
end
local MySpeed = Vector3.new(Body.Velocity.X, 0, Body.Velocity.Z).magnitude
local VelocityDifference = math.abs((MySpeed - (ThrustForce.velocity.magnitude)))
if MySpeed > 3 and ThrustForce.velocity.magnitude > 3 and VelocityDifference > (0.7 * ThrustForce.velocity.magnitude) then
CurrentSpeed.Movement = (CurrentSpeed.Movement * 0.9)
end
if Controls.Forward.Mode then --Handle acceleration
CurrentSpeed.Movement = math.min(MaxSpeed.Movement.Max, (CurrentSpeed.Movement + (MaxSpeed.Acceleration * Rate)))
end
if Controls.Backward.Mode then --Handle deceleration, if speed is more than 0, decrease quicker.
CurrentSpeed.Movement = math.max(-MaxSpeed.Movement.Min, (CurrentSpeed.Movement - (MaxSpeed.Deceleration * ((CurrentSpeed.Movement > 0 and 2.8) or 1) * Rate)))
end
if Controls.Left.Mode then --Handle left turn speed
CurrentSpeed.Turn = math.min(Speed.TurnSpeed.Speed.Max, (CurrentSpeed.Turn + (Speed.TurnSpeed.TurnAlpha)))
end
if Controls.Right.Mode then --Handle right turn speed
CurrentSpeed.Turn = math.max(-Speed.TurnSpeed.Speed.Min, (CurrentSpeed.Turn - (Speed.TurnSpeed.TurnAlpha)))
end
local Direction = UpperTorso.CFrame.lookVector
Direction = Vector3.new(Direction.x, 0, Direction.z).unit
local Velocity = (Direction * CurrentSpeed.Movement) --The thrust force which you move.
ThrustForce.velocity = Vector3.new(Velocity.X, ThrustForce.velocity.Y, Velocity.Z)
local LeanAmount = (-CurrentSpeed.Turn * (math.pi / 6) / 4) --Amount your character leans over.
local XZAngle = math.atan2(UpperTorso.CFrame.lookVector.z, 0, UpperTorso.CFrame.lookVector.x) --Handle rotation
TurnGyro.cframe = CFrame.Angles((LeanAmount * Direction.x), 0, (LeanAmount * Direction.z))
--Wheel animation
local DesiredAngle = (999999999 * (-CurrentSpeed.Movement / math.abs(CurrentSpeed.Movement)))
local MaxVelocity = (CurrentSpeed.Movement / 250)
for i, v in pairs({FrontMotor, BackMotor}) do
if v and v.Parent then
v.DesiredAngle = DesiredAngle
v.MaxVelocity = MaxVelocity
end
end
--Smoke exhaust from vehicle running.
for i, v in pairs(ExhaustSmoke) do
if v and v.Parent then
v.Opacity = ((math.min(math.abs(CurrentSpeed.Movement), 10) / 10) * 0.5)
end
end
--Engine running sound which pitch changes while in motion.
Sounds.Engine.Pitch = (1 + (math.abs(CurrentSpeed.Movement / MaxSpeed.Movement.Max) * 1))
wait(Rate)
end
end
function SpawnVehicle()
Handle.Transparency = 1
Spawn(function()
InvokeClient("PlaySound", Sounds.Engine)
InvokeClient("PlayAnimation", Animations.Hold)
end)
Humanoid.PlatformStand = true
local VehicleData = Assets.CreateVehicle()
Body = VehicleData.Vehicle
local ParticleTable = VehicleData.Tables
--FrontMotor = Body.FrontMotor
--BackMotor = Body.BackMotor
ExhaustSmoke = ParticleTable.ExhaustSmoke
Lights = ParticleTable.Lights
Sparkles = ParticleTable.Sparkles
if SpeedBoost.Active then
for i, v in pairs(Sparkles) do
if v and v.Parent then
v.Enabled = true
end
end
end
local UpperTorsoWeld = Instance.new("Weld")
UpperTorsoWeld.C0 = PoseOffset
UpperTorsoWeld.Part0 = UpperTorso
UpperTorsoWeld.Part1 = Body
UpperTorsoWeld.Parent = Body
Body.CanCollide = true
RotationForce = Instance.new("BodyAngularVelocity")
RotationForce.maxTorque = Vector3.new(0, math.huge, 0)
RotationForce.angularvelocity = Vector3.new(0, 0, 0)
RotationForce.Parent = UpperTorso
ThrustForce = Instance.new("BodyVelocity")
ThrustForce.maxForce = Vector3.new(math.huge, 0, math.huge)
ThrustForce.velocity = Vector3.new(0, 0, 0)
ThrustForce.P = 100
ThrustForce.Parent = UpperTorso
TurnGyro = Instance.new("BodyGyro")
TurnGyro.maxTorque = Vector3.new(5000, 0, 5000)
TurnGyro.P = 300
TurnGyro.D = 100
TurnGyro.Parent = UpperTorso
Body.Parent = Tool
local RayHit, RayPos, RayNormal = RayCast(UpperTorso.Position, Vector3.new(0, -1, 0), (UpperTorso.Size.Y * 2), {Character})
if RayHit then
UpperTorso.CFrame = UpperTorso.CFrame + Vector3.new(0, ((Character:GetModelSize().Y / 2) + 1.5), 0)
end
Spawn(ThrustUpdater)
end
function FreezePlayer()
if CheckIfAlive() then
local FreezePart = BasePart:Clone()
FreezePart.Name = "FreezePart"
FreezePart.Transparency = 1
FreezePart.Anchored = true
FreezePart.CanCollide = false
local FreezeWeld = Instance.new("Weld")
FreezeWeld.Part0 = UpperTorso
FreezeWeld.Part1 = FreezePart
FreezeWeld.Parent = FreezePart
Debris:AddItem(FreezePart, 0.125)
FreezePart.Parent = Character
UpperTorso.Velocity = Vector3.new(0, -25, 0)
UpperTorso.RotVelocity = Vector3.new(0, 0, 0)
end
end
function CleanUp()
Handle.Velocity = Vector3.new(0, 0, 0)
Handle.RotVelocity = Vector3.new(0, 0, 0)
for i, v in pairs({}) do
if v then
v:disconnect()
end
end
for i, v in pairs({Body, RotationForce, ThrustForce, TurnGyro}) do
if v and v.Parent then
v:Destroy()
end
end
for i, v in pairs(Tool:GetChildren()) do
if v:IsA("BasePart") and v ~= Handle then
v:Destroy()
end
end
end
function CheckIfAlive()
return (((Character and Character.Parent and Humanoid and Humanoid.Parent and Humanoid.Health > 0 and UpperTorso and UpperTorso.Parent and Player and Player.Parent) and true) or false)
end
function Equipped(Mouse)
Character = Tool.Parent
Player = Players:GetPlayerFromCharacter(Character)
Humanoid = Character:FindFirstChild("Humanoid")
UpperTorso = Character:FindFirstChild("UpperTorso")
if not CheckIfAlive() then
return
end
Spawn(CleanUp)
Spawn(EnableFirstPersonView)
Spawn(SpawnVehicle)
ToolEquipped = true
end
function Unequipped()
Spawn(CleanUp)
Spawn(FreezePlayer)
for i, v in pairs(Sounds) do
v:Stop()
Spawn(function()
InvokeClient("StopSound", v)
end)
end
if CheckIfAlive() then
Humanoid.PlatformStand = false
end
Handle.Transparency = 0
ToolEquipped = false
end
function OnServerInvoke(player, mode, value)
if player == Player and ToolEquipped and value and CheckIfAlive() then
if mode == "KeyPress" then
local Down = value.Down
local Key = value.Key
local ByteKey = string.byte(Key)
for i, v in pairs(Controls) do
if Key == v.Key or ByteKey == v.ByteKey then
Controls[i].Mode = Down
end
end
if Key == " " and Down then --Jump controller
if math.abs(tick() - Jump.LastJump) > Jump.ReloadTime and not Jump.Jumping and ThrustForce and ThrustForce.Parent then
Jump.Jumping = true
local Parts = GetAllConnectedParts(Body)
local Mass = 0
for i, v in pairs(Parts) do
Mass = (Mass + v:GetMass())
end
ThrustForce.maxForce = Vector3.new(ThrustForce.maxForce.X, ((Mass * Gravity) * 100), ThrustForce.maxForce.Z)
ThrustForce.velocity = (Vector3.new(0, 1, 0) * Jump.JumpForce) + Vector3.new(ThrustForce.velocity.X, 0, ThrustForce.velocity.Z)
wait(0.1)
ThrustForce.maxForce = Vector3.new(ThrustForce.maxForce.X, 0, ThrustForce.maxForce.Z)
ThrustForce.velocity = Vector3.new(ThrustForce.velocity.X, 0, ThrustForce.velocity.Z)
Jump.LastJump = tick()
Jump.Jumping = false
end
elseif Key == "x" and Down then --Toggle light(s) on/off.
for i, v in pairs(Lights) do
if v and v.Parent then
v.Enabled = not v.Enabled
end
end
elseif Key == "h" and Down then --Play honk sound.
local Sound = Sounds.Honk
if (tick() - Honk.LastHonk) >= (Sound.TimeLength + Honk.ReloadTime) and not Honk.Honking then
Honk.Honking = true
local TempSound = Sound:Clone()
Debris:AddItem(TempSound, Sound.TimeLength)
TempSound.Parent = Body
TempSound:Play()
Honk.LastHonk = tick()
Honk.Honking = false
end
elseif Key == "q" and Down then --Activate special.
if not Special.Allowed or not Special.Enabled or Special.Active then
return
end
Special.Enabled = false
Special.Active = true
wait(Special.Duration)
Special.Active = false
wait(Special.ReloadTime)
Special.Enabled = true
elseif ByteKey == 48 and Down then --Activate speed boost.
if not SpeedBoost.Allowed or not SpeedBoost.Enabled or SpeedBoost.Active then
return
end
SpeedBoost.Enabled = false
SpeedBoost.Active = true
for i, v in pairs(Sparkles) do
if v and v.Parent then
v.Enabled = true
end
end
MaxSpeed.Acceleration = Speed.Acceleration.Boost
MaxSpeed.Deceleration = Speed.Deceleration.Boost
MaxSpeed.Movement = Speed.MovementSpeed.Boost
wait(SpeedBoost.Duration)
MaxSpeed.Acceleration = Speed.Acceleration.Normal
MaxSpeed.Deceleration = Speed.Deceleration.Normal
MaxSpeed.Movement = Speed.MovementSpeed.Normal
for i, v in pairs(Sparkles) do
if v and v.Parent then
v.Enabled = false
end
end
SpeedBoost.Active = false
wait(SpeedBoost.ReloadTime)
SpeedBoost.Enabled = true
end
end
end
end
function InvokeClient(Mode, Value)
local ClientReturn = nil
pcall(function()
ClientReturn = ClientControl:InvokeClient(Player, Mode, Value)
end)
return ClientReturn
end
Spawn(CleanUp)
ServerControl.OnServerInvoke = OnServerInvoke
Tool.Equipped:connect(Equipped)
Tool.Unequipped:connect(Unequipped)
I found it. Freezingplayer is the culprit. I took out "Spawn(FreezePlayer)" when it is unequipped and it works.
function Unequipped()
Spawn(CleanUp)
---Spawn(FreezePlayer)

Check Winner Naughts and Crosses game - Lua/Corona

I am quite new to the Lua language and am trying to create a simple Tic Tac Toe game. I am having difficulties figuring out how to check the winner. I have tried if-then statements but I think I am using them wrong. Not sure what the best way to check the winner is so any suggestions or assistance is greatly appreciated.
The code is -
local composer = require( "composer" )
local scene = composer.newScene()
d = display
w20 = d.contentWidth * .2
h20 = d.contentHeight * .2
w40 = d.contentWidth * .4
h40 = d.contentHeight * .4
w60 = d.contentWidth * .6
h60 = d.contentHeight * .6
w80 = d.contentWidth * .8
h80 = d.contentHeight * .8
----DRAW LINES FOR BOARD
local lline = d.newLine(w40,h20,w40,h80 )
lline.strokeWidth = 5
local rline = d.newLine(w60,h20,w60,h80 )
rline.strokeWidth = 5
local bline = d.newLine(w20,h40,w80,h40 )
bline.strokeWidth = 5
local tline = d.newLine(w20,h60,w80,h60 )
tline.strokeWidth = 5
--PLACE BOARD COMPARTMENT DIMENSIONS IN TABLE
board ={
{"tl",1,w20,h40,w40,h20,0},
{"tm",2,w40,h40,w60,h20,0},
{"tr",3,w60,h40,w80,h20,0},
{"ml",4,w20,h60,w40,h40,0},
{"mm",5,w40,h60,w60,h40,0},
{"mr",6,w60,h60,w80,h40,0},
{"bl",7,w20,h80,w40,h60,0},
{"bm",8,w40,h80,w60,h60,0},
{"br",9,w60,h80,w80,h60,0}
}
--
local EMPTY, X, O = 0, 1, 2
local whichTurn = 0
--FILL COMPARTMENT W/ COLOUR WHEN TOUCHED
local function fill(event)
if (event.phase == "ended") then
for t = 1,9 do
if event.x > board[t][3] and event.x < board[t][5] then
if event.y < board[t][4] and event.y > board[t][6] then
if board[t][7] == EMPTY then
if whichTurn == 1 then
whichTurn = 2
else
whichTurn = 1
end
board[t][7] = whichTurn
if board[t][7] == 1 then
local xText = display.newText("X", board[t][3], board[t][4], "Arial", 80)
xText.anchorX = 0
xText.anchorY = 100
elseif board[t][7] == 2 then
local oText = display.newText("O", board[t][3], board[t][4], "Arial", 80)
oText.anchorX = 0
oText.anchorY = 100
end
end
end
end
end
end
local function checkWinner()
for i = 1,9 do
if board[i][2] == 1 and board[i][7] == 1 then
boxOne = "x"
end
if board[i][2] == 2 and board[i][7] == 1 then
boxTwo = "x"
end
if board[i][2] == 3 and board[i][7] == 1 then
boxThree = "x"
end
if boxOne == "x" and boxTwo == "x" and boxThree == "x" then
display.newText("Winner", 10, 100, "Arial", 200)
end
end
end
end
Runtime:addEventListener ("touch", fill)
return scene
local All_Lines = {{1,5,9}, {3,5,7}, {1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8}, {3,6,9}}
local function checkWinner()
for _, Line in ipairs(All_Lines) do
local values = 0
for _, idx in ipairs(Line) do
values = values * 10 + board[idx][7]
end
if values == 111 then
display.newText("Winner", 10, 100, "Arial", 200)
return
elseif values == 222 then
display.newText("Loser", 10, 100, "Arial", 200)
return
end
end
end

Corona SDK / Lua : An table's property is nil, when accessed via event.other during collision event. But why?

So I have this module, where all of its activity during the game is in. In t.physics I add a collision event listener (differentiating if target is a group or a single object). When the concerning objects detect a collision though, the property col of the other object (event.other) seems to be nil, although I initially set it to a string representing a color in t.create. I just can't find the cause for that, can anyone?
Thanks for your help.
Greetings, Nils
local fence = require("lib.fence")
local physics = require("physics")
local t = {}
local stages = {yellow = 1, lila = 1, red = 1}
local sizes = {1, 3.625, 7.25}
t.colors = {"yellow", "lila", "red"}
t.growing = false
t.setSize = function(fill)
local tHeight = fill.contentHeight * sizes[stages[fill.col]]
local tScale = tHeight / fill.contentHeight
fill.yScale = tScale
end
t.grow = function(group, color, hero)
local counter = 0
stages[color] = stages[color] + 1
for i = 1, group.numChildren, 1 do
if group[i].col == color then
counter = counter + 1
local function newPhysics() t.physics(group) end
if counter == 1 then
local function reset() t.growing = false if stages[color] == 3 then stages[color] = 1; newPhysics(); end end
local function start() t.growing = true end
transition.to(group[i], {time = 260, yScale = sizes[stages[color]], onStart = start, onComplete = reset})
else
transition.to(group[i], {time = 250, yScale = sizes[stages[color]], onStart = start})
end
end
end
end
t.physics = function(target)
if target.numChildren == nil then
physics.removeBody(target)
local function add()
physics.addBody( target, "static", {isSensor = true} )
target.collision = function(self, event)
if event.phase == "began" then
target.count = target.count + 1
if target.count == 1 then
t.grow(target.parent, self.col, event.other)
end
elseif event.phase == "ended" then
target.count = 0
end
end
end
timer.performWithDelay(1, add, 1)
else
for i = 1, target.numChildren, 1 do
physics.removeBody( target[i] )
physics.addBody( target[i], "static", {isSensor = true} )
target[i].name = "fill"
local fill = target[i]
fill.count = 0
fill.collision = function(self, event)
if event.phase == "began" then
self.count = self.count + 1
if self.count == 1 and event.other.x ~= nil then
t.grow(target, self.col, event.other)
end
else
fill.count = 0
end
end
fill:addEventListener("collision")
end
end
end
t.setColor = function(fill)
local colors = {
{238 / 255, 228 / 255, 28 / 255},
{38 / 255, 33 / 255, 77 / 255},
{175 / 255, 24 / 255, 52 / 255},
}
local names = {"yellow", "lila", "red"}
local r = math.random(3)
fill.fill = colors[r]
fill.col = names[r]
end
t.create = function(fences, group, colors)
local fills = {}
for i = 1, #fences, 1 do
local rCol = math.random(3)
local col
if rCol == 1 then
col = colors.yellow
elseif rCol == 2 then
col = colors.lila
else
col = colors.red
end
fills[i] = display.newRect(
group, fences[i].x + fences[i].contentWidth * 0.125, fences[i].y,
fences[i].contentWidth * 0.9, (fences[i].contentHeight * 0.5 / 3)
)
fills[i].dPosX = fills[i].x
fills[i].y = display.contentHeight- fills[i].contentHeight / 2
fills[i].fill = col
fills[i].col = t.colors[rCol]
fills[i].increased = false
end
return fills
end
t.move = function(fills, fences, group)
for i = 1, #fills, 1 do
local fill = fills[i]
function fill:enterFrame()
self:translate(fence.speed, 0)
if t.growing == false then
t.setSize(self)
end
if self.x > display.contentWidth + 0.55 * fences[i].contentWidth then
local xT = {}
for i = 1, group.numChildren, 1 do
xT[i] = group[i].x
end
local function compare(a, b) return a < b end
table.sort(xT, compare)
self.x = xT[1] - fences[i].contentWidth * 0.98
t.setColor(self)
local function newPhysics() t.physics(self) end
timer.performWithDelay( 25, newPhysics, 1 )
self:toBack()
end
end
Runtime:addEventListener("enterFrame", fill)
end
end
return t
Solved. Ugh, sorry, I forgot to define the property on the other object involved (hero), that has its own module. What a stupid slip.
Thanks for your answers anyways!
You don't seem to have any dynamic bodies here. What is colliding with what? Could it be that the other object involved in the collision (the value of event.other) is not something initialized in t.create() and so doesn't have the col property?
From the Corona documentation on Collision Detection:
Some body types will — or will not — collide with other body types. In a collision between two physical objects, at least one of the objects must be dynamic, since this is the only body type which collides with any other type.
Also, in your fill.collision(), I think you want to pass event.target as the first argument to t.grow() rather than target. If you try things, please update the question with more information.

Error: attempt to index global 'playerBul' (a nil value)

The error is saying:
game.lua:171: attempt to index global 'playerBul' (a nil value)
Sorry if I put too much unnecessary code, I just do not know what is causing this error.
here are all the files for this game:
menu.lua:
local menu = {}
local bannermenu;
local selection;
menu.name = 'Menu'
local function play()
mode = require('game')
mode.load()
end
local options = {
{['text'] = 'Play', ['action'] = play},
{['text'] = 'Exit', ['action'] = love.event.quit}
}
function menu.load()
bannermenu = love.graphics.newImage(BANNER)
selection = 1
pointer = love.graphics.newImage(POINTER)
mode = menu
end
function menu.update()
return mode
end
function menu.draw()
love.graphics.draw(bannermenu, 200,10)
for i = 1,#options do
if i == selection then
love.graphics.draw(pointer, 300, 200 + i *20)
end
love.graphics.printf(options[i].text,0,200 + i * 20, love.graphics.getWidth(), 'center')
end
end
function menu.keypressed(key)
if key == "up" then
selection = (selection - 2)%(#options) + 1
elseif key == "down" then
selection = (selection) % (#options) + 1
elseif key == "return" then
options[selection].action()
elseif key == "escape" then
love.event.quit()
end
end
return menu
main.lua
TITLE = 'Die Aliens Die!'
PLAYER_BULLET = 'Images/playerbullet.png'
ENEMY_BULLET = 'Images/enemybullet.png'
HEALTH_IMG = 'Images/life.png'
ENEMY_UFO = {
ENEMY_1 = 'Images/enemy1.png',
ENEMY_2 = 'Images/enemy2.png',
ENEMY_3 = 'Images/enemy3.png'
}
PLAYER_IMG = 'Images/spaceship.png'
YOU_WIN = 'Images/win.png'
BANNER = 'Images/banner.png'
POINTER = 'Images/pointer.png'
function love.load()
love.window.setTitle(TITLE)
mode = require "menu"
mode.load()
end
function love.draw()
mode.draw()
end
function love.keypressed(key, isrepeat)
mode.keypressed(key)
end
function love.update(dt)
mode.update(dt)
end
game.lua
local game = {}
local playerShip = {}
local alienUFO = {}
local bullets = {}
local alienBullets = {}
local playerBullets = {}
local aliens = {{},{},{},{},{},{},{},{},{},{}}
local health = 3
local score = 0
local level = 1
local alienMovement = true
local healthImage;
local alienQty = 0
local pause
--local function gameOver()
--local function gamwWin()
local function clearTable(t)
for i = #t,1,-1 do
table.remove(t,i)
end
end
local function clearAliens()
for i=#aliens,1,-1 do
for j = #aliens[i],1,-1 do
table.remove(aliens[i],j)
end
end
end
local function insertAliens()
alienQty = 0
for i=1,4 do
for j =1,10 do
local alien = {}
alien.x = (j-1) *alienUFO.width + 10
alien.y = (j-1) *alienUFO.width + 35
if level ==2 then
alien.life = 2
if level == 3 then
alien.life = 3
end
table.insert(aliens[j], alien)
alienQty = alienQty + 1
end
end
end
end
local function initGame()
clearTable(playerBullets)
clearTable(alienBullets)
clearAliens()
insertAliens()
playerShip.x = love.graphics.getWidth() / 2 - playerShip.width /2
end
local function playerShoot()
local bullet = {}
playerShip.x = playerShip.x + 32
playerShip.y = playerShip.y + 10
table.insert(playerBullets, bullet)
end
local function AlienShoot(x,y)
local bullet = {}
bullet.x = alienUFO.width/2
bullet.y = y -5
table.insert(alienBullets, bullet)
end
local function playerShots(dt)
if next(playerBullets) ~= nil then
for i = #playerBullets,1,-1 do
playerBullets[i].y = playerBullets[i].y - dt* playerBullets.bulletSpeed
if playerBullets[i].y < 0 then
table.remove(playerBullets,i)
else
for j = #aliens, 1,-1 do
for k = #aliens[j],1,-1 do
if next(playerBullets) ~= nil and playerBullets[i] ~= nil and
aliens[j][k].x <= playerBullets[i].x and aliens[j] [k].x + 50 >= playerBullets[i].x
and aliens[j][k].y <= playerBullets[i].y and aliens[j] [k].y + 47 >= playerBullets[i].y then
table.remove(playerBullets, i)
if level == 2 and aliens[j][k].life > 0 then
aliens[j][k].life = aliens[j][k].life - 1
if level == 3 and aliens[j][k].life > 0 then
aliens[j][k].life = aliens[j][k].life - 1
else
table.remove(aliens[j], k)
alienQty = alienQty - 1
score = score + 100
end
break
end
end
end
end
end
end
end
local function PlayerShot()
health = health - 1
if health == 0 then
love.event.quit() -- COME BACK HERE FOR LOSE
end
end
local function AlienShots(dt)
if next(alienBullets) ~= nil then
for i = #alienBullets,1,-1 do
alienBullets[i].y = alienBullets[i].y + dt * alienUFO.bulletSpeed
if alienBullets[i].y > love.graphics.getHeight() then
table.remove(alienBullets, i)
elseif playerShip.x <= alienBullets[i].x and playerShip.x + playerShip.width >= alienBullets[i].x
and playerShip.y <= alienBullets[i].y and playerShip.y + playerShip.height >- alienBullets[i].y then
table.remove(alienBullets, i)
PlayerShot()
end
end
end
end
local function nextLVL()
level = level + 1
if level == 2 then
alienUFO.image = love.graphics.newImage(alienUFO.ENEMY1)
alienUFO.speed = 100
alienUFO.shotProb = 20
alienUFO.bullet = alienBul.image
initGame()
elseif level == 3 then
alienUFO.image = love.graphics.newImage(alienUFO.ENEMY2)
initGame()
elseif level > 3 then
love.event.quit() -- COME BACK HERE FOR WIN
end
end
function game.load()
pause = false
level = 1
health = 3
score = 0
playerShip.speed = 300
playerShip.bulletSpeed = 300
playerShip.width = 75
playerShip.height = 71
alienUFO.speed = 70
alienUFO.width = 50
alienUFO.height = 47
alienUFO.ENEMY1 = ENEMY_UFO.ENEMY_1
alienUFO.ENEMY2 = ENEMY_UFO.ENEMY_2
alienUFO.ENEMY3 = ENEMY_UFO.ENEMY_3
alienUFO.bulletSpeed = 300
alienUFO.image = love.graphics.newImage(alienUFO.ENEMY3)
playerShip.IMAGE = PLAYER_IMG
playerShip.image = love.graphics.newImage(playerShip.IMAGE)
healthImage = love.graphics.newImage(HEALTH_IMG)
playerShip.x = love.graphics.getWidth() / 2 - playerShip.width/2
playerShip.y = love.graphics.getHeight() - 100
playerBul.image = love.graphics.newImage(PLAYER_BULLET)
alienBul.image = love.graphics.newImage(ENEMY_BULLET)
initGame()
end
function game.draw()
if pause then
love.graphics.print('GAME PAUSED',love.graphics.getWidth()/2 - 20,20)
end
if next(playerBullets) ~= nil then
for i = 1, #playerBullets do
love.graphics.draw(playerBul.image, playerBullets[i].x, playerBullets[i].y)
end
end
if next(alienBullets) ~= nil then
for i = 1, #alienBullets do
love.graphics.draw(alienBul.image, alienBullets[i].x, alienBullets[i].y)
end
end
if next(aliens) ~= nil then
for i = 1, #aliens do
for j = 1, #aliens[i] do
love.graphics.draw(alienUFO.image, aliens[i][j].x, aliens[i][j].y)
end
end
end
love.graphics.print('Score: '..score, love.graphics.getWidth() - 100,20)
love.graphics.draw(playership.image, playership.x, playerShip.y)
for i = 1, lives do
love.graphics.draw(healthImage, 10+ 1 * 15,20)
end
end
function game.update(dt)
if not pause then
if alienQty == 0 then
nextLVL()
end
if love.keyboard.isDown("right") then
playerShip.x = playerShip.x + dt * playerShip.speed
elseif love.keyboard.isDown("left") then
playerShip.x = playerShip.x - dt * playerShip.speed
end
if love.keyboard.isDown(" ") then
playerShoot()
end
playerShots(dt)
AlienShots(dt)
if love.math.random(1,100) < alienUFO.shotProb then
local r = love.math.random(1,#aliens)
if next(aliens[r]) ~= nil then
alienShoot(aliens[r][#aliens[r]].x, aliens[r][#aliens[r]].y)
end
end
if alienMovement then
for i = 1, #aliens do
for j = 1, #aliens[i] do
aliens[i][j].x = aliens[i][j].x + dt * alienUFO.speed
if aliens[i][j].x + alienUFO.width + 2 >= love.graphics.getWidth() then
alienMovement = false
end
end
end
else
for i =1, #aliens do
for j = 1, #aliens[i] do
aliens[i][j].x = aliens[i][j].x - dt * alienUFO.speed
if aliens[i][j].x - 2 <= 0 then
alienMovement = true
end
end
end
end
if playerShip.x < 0 then
playerShip.x = 0
elseif playerShip.x > love.graphics.getWidth() - 75 then
playerShip.x = love.graphics.getWidth() -75
end
end
end
end
function game.keypressed(key)
if key =='p' then
pause = not pause
end
end
return game
you haven't defined a load function on the game table you return in game.lua. it looks like you already wrote the load logic but wrote it as a local function named loadGame. to fix your issue update game.lua to export the load function and just have it call the load function you've already created, like this:
function game.load()
loadGame()
end
somewhere before you return the game table in game.lua, say after your definition of game.keypressed
or you could alternatively just change local function loadGame() to function game.load() to remove the local function and redefine it as exported functionality

Lua - Replay button?

I'm making an app using Corona SDK. In the game you have to touch all the spheres in time and if you win, a you win image appears. I made a replay button under the "you win" message, but how do I say him to restart the whole game?
Here is the code (not all of it):
function winLose(condition)
if condition == "Win" then
print ("Winner")
winMSG = display.newImage("media/win.png")
-- Replay button
local btnReplay = ui.newButton{
default = "media/buttonWhite.png",
over = "media/buttonWhiteOver.png",
onPress = btnReplayPress,
onRelease = btnReplayRelease,
text = "Replay",
textColor = { 0, 0, 0, 255 },
size = 26,
id = "replay",
emboss = true
}
btnReplay.x = _W/2;
btnReplay.y = _H/2 + 50;
elseif condition == "Fail" then
print ("Loser")
loseMSG = display.newImage("media/lose.png")
-- Replay Button
btnReplay = ui.newButton{
default = "media/buttonWhite.png",
over = "media/buttonWhiteOver.png",
onPress = btnReplayPress,
onRelease = btnReplayRelease,
textColor = { 0, 0, 0, 255 },
size = 26,
text = "Replay"
id = "replay",
emboss = true
}
-----
function btnReplay:touch(e)
if e.phase == "began" then
--
elseif e.phase == "moved" then
--
elseif e.phase == "ended" then
-- Here I should say what it has to do to replay
end
end
-----
btnReplay:addEventListener( "touch", btnReplay);
-----
btnReplay.x = _W/2;
btnReplay.y = _H/2 + 50;
end
end
local function trackOrbs(obj)
obj:removeSelf()
o = o-1;
if time_up ~= true then
if (o == 0) then
timer.cancel(gametmr);
winLose("Win");
end
end
end
local function countDown (e)
if (time_remain == total_secs) then
ready = true
end
time_remain = time_remain - 1;
countdowntxt.text = time_remain;
if time_remain == 0 then
time_up = true
if o ~= 0 then
winLose("Fail");
ready = false;
end
end
end
local function spawnOrb()
local orb = display.newImageRect("media/orb.png", 60, 60);
orb:setReferencePoint(display.CenterReferencePoint);
orb.x = mRand(50, _W-50); orb.y = mRand (50, _H-50);
function orb:touch(e)
if time_up ~= true then
if (ready == true) then
if (e.phase == "ended") then
trackOrbs(self);
end
end
end
return true
end
o = o + 1;
orb:addEventListener("touch", orb);
if (o == total_orbs) then
gametmr = timer.performWithDelay(1000, countDown, total_secs) ;
else
ready = false
end
end
tmr = timer.performWithDelay (20, spawnOrb, total_orbs);
You can have a while loop like this
while true do
if mainGame then
--game code
elseif done then
--buttons
if button.restart then
mainGame = true
end
end
end

Resources