Update sprites nested in groups - lua

How do I update or manipulate a sprite nested in several groups?
I first tried to add the "enterFrame" event directly to the desired class with the sprite (without success)
My code
local box = {}
-- PUBLIC FUNCTIONS
function box:new( )
local group = display.newGroup()
local image = display.newImage("crate.png")
group:insert(image)
function group:update()
image.rotation = image.rotation + 1
end
return group
end
return box
Second I though of adding a
Runtime:addEventListener("enterFrame", enterFrame)
in my scene, then looping through the groups added to the scene (scene.view) and call a custom update-function there that sends the update forward until it reaches my class. However I have not found a way of checking if the group has a update method or not. Now I just call update even if the group does not have it.
function enterFrame (event)
local group = scene.view
for i=1,group.numChildren do
group[i]:update()
end
end

local box = {}
You can try this simple solution
-- PUBLIC FUNCTIONS
function box:new( )
local group = display.newGroup()
local image = display.newImage("crate.png")
group:insert(image)
group.isThereUpdate = true
// or group.isThereUpdate = false
function group:update()
image.rotation = image.rotation + 1
end
return group
end
return box
function enterFrame (event)
local group = scene.view
for i=1,group.numChildren do
if group[i].isThereUpdate then
group[i]:update()
end
end
end

Related

Lua Roblox respawn character dead

How should I make this code work? The Judoon character must regenerate, (respawn) when I click on the wall but only when he is dead.[![Regenerate][1]][1] When I click on the wall, my Judoon character has to respawn but only when he is dead.
Also how can I introduce Regen Button, the script, be separate from the Judoon model, but it should work. If you put the script Regen into Workspace, separate from the Judoon folder, it will not work.
local box = script.Parent
local debounce = false
-- DO NOT GROUP THIS WITH YOUR MODEL!
local everything = {Judoon}
local names = {Judoon}
local children = game.Workspace:children()
for i=1,#children do
if (children[i].Name == "Judoon") then -- Replace the name with your models's name.
table.insert(everything, children[i]:clone())
table.insert(names, children[i].Name)
end
end
function regen()
for i=1,#everything do
game.Workspace:findFirstChild(names[i]):remove() -- Dont mess with this stuff.
new_thing = everything[i]:clone()
new_thing.Parent = game.Workspace
new_thing:makeJoints()
end
end
function onClicked()
if Judoon:FindFirstChild("Judoon"):GetState() == Enum.HumanoidStateType.Dead then
regen()
end
end
wait(15)-- This is how long it takes untill the regen button will work again.
script.Parent.BrickColor = BrickColor.new(104)
debounce = false
end
script.Parent.ClickDetector.MouseClick:connect(onClicked)
--This regen button was made by andymewborn,hope you like(d) it!
[1]: https://i.stack.imgur.com/HhLo3.png
You can do something like this, if the humanoid is dead then regenerate.
function onClicked()
if Judoon:FindFirstChild("Judoon"):GetState() == Enum.HumanoidStateType.Dead then
regen()
end
end
New edit:
--[[
1. Put this script inside the button
2. Rename the modelname
3. The model must be a child of Workspace
--]]
button = script.Parent
modelname = "Pk" -- Model name
model = game.Workspace:FindFirstChild(modelname)
backup = model:Clone()
function Regen()
local Old =game.Workspace:FindFirstChild(modelname)
Old:Destroy()
local New = backup:Clone()
model = New -- new changes made here
New.Parent = workspace
New:MakeJoints()
end
function onClicked()
if button.BrickColor == BrickColor.new("Bright violet") then
if model:FindFirstChild("Humanoid") ~= nil then
if model.Humanoid:GetState() == Enum.HumanoidStateType.Dead then
Regen()
print("removed and added")
end
end
button.Regen:Play()
button.BrickColor = BrickColor.new("Really black")
wait(3)
button.BrickColor = BrickColor.new("Bright violet")
end
end
button.ClickDetector.MouseClick:Connect(onClicked)

Remove Corona SDK element / function

has form.lua file with code
local _M = {}
function _M.calc( a )
local quad = display.newRect(100,100,100,100)
end
return _M
and the file scene2.lua with the code
local form = require "form"
form.calc( )
I need the "quad / function" to be removed from the screen when it goes to another scene.
Add display object to scene group so composer remove it for you.
form.lua
local _M = {}
function _M.calc( group )
local quad = display.newRect( group, 100,100,100,100)
end
return _M
scene2.lua
local form = require "form"
form.calc( scene.view )

How to implement this pattern in Lua with Cocos2d-x

I wanna call GameScene setSpecificSquare function in Square, it will occur 'attempt to index field 'squares' error.
In my understanding, require("GameScene") in onTouchEnded(touch event) do not get the last variable of GameScene, it has not been constructed, so it does not have squares attribute.
How to call GameScene static function setSpecificSquare in Square? Or in other word, how to get the last GameScene so I can set self.squares table?
Thanks in advanced!! :)
Square.lua
require "Cocos2d"
require "Cocos2dConstants"
local Square = class("Square",function()
return cc.Node:create()
end)
function Square.create()
local square = Square.new()
return square
end
function Square:ctor()
self.bg = cc.Sprite:create("square_bg.png")
self:addChild(self.bg)
self.isHighlight = true
local function onTouchEnded(touch,event)
--occur error here
require("GameScene"):setSpecificSquare()
end
end
return Square
GameScene.lua
require "Cocos2d"
require "Cocos2dConstants"
local GameScene = class("GameScene",function()
return cc.Scene:create()
end)
function GameScene.create()
local scene = GameScene.new()
return scene
end
function GameScene:ctor()
self.visibleSize = cc.Director:getInstance():getVisibleSize()
self.x = cc.Director:getInstance():getVisibleOrigin().x
self.y = cc.Director:getInstance():getVisibleOrigin().y
self.squares = {}
for i=0, 5 do
self.squares[i] = {} -- create a new row
for j=0, 5 do
self.squares[i][j] = nil
end
end
--add layer
self.bombLayer = cc.Layer:create()
self:addChild(self.bombLayer)
--add squares
self:addSquares()
end
function GameScene:addSquares()
for i=0,5 do
for j=0,5 do
local square = require("src/Square"):create()
square:setPosition(0+j*70,0+i*70)
self.bombLayer:addChild(square)
self.squares[i][j] = square
end
end
end
function GameScene:setSpecificSquare()
--can not access self.square here, occur attempt to index field 'squares' error
self.square[0][0].isHighLight
end
return GameScene
Move self.squares = {} out of ctor function, or call ctor function before calling addSquares, or you can just call this function inside addsquares.
The recommended method is moving it out of function and creating it on creation of your GameScene object:
require "Cocos2d"
require "Cocos2dConstants"
local GameScene = class("GameScene",function()
return cc.Scene:create()
end)
function GameScene.create()
local scene = GameScene.new()
return scene
end
GameScene.squares = {}
...

Corona Sdk - Is there a way to call and group:insert() an object from another lua file?

As stated in the title I would like to not only call an object from an external Lua file, but I would also like to group:insert() this object into my Menu page with the properties given to it in the external lua file. Is this possible and/or efficient? I would just really like to make sure data isn't repeated through out my project.
EDIT
Here's my code so far:
The group:insert() function is throwing me an error stating it was expecting a table and that I might have been trying to call a function in which case i should use ":" instead of "."
This is menu.lua:
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local widget = require "widget"
local m = require ("myData")
local menuFunction = require("menuFunction")
local menuSwipe
-- =======================
-- menuSwipe()
-- =======================
menuSwipe = function(self, event)
local phase = event.phase
local touchID = event.id
if(phase == "began") then
elseif(phase == "moved") then
elseif(phase == "ended" or phase == "cancelled") then
if(m.menuActivator > 0) then
menuDown(m.invisiBar, event)
else
--m.layerInfo = layers
transition.to( menuFunction.menuBar, { x = menuFunction.menuBar.x, y = 0, time = 200 } )
--transition.to( layers, { x = menuFunction.menuBar.x, y = h, time = 100 } )
m.invisiBar = display.newRect( 0,0,w,25,6)
m.invisiBar.alpha = 0
m.menuActivator = 1
end
end
end
-- ++++++++++++++++++++++
-- menuDown()
-- ++++++++++++++++++++++
function menuDown(self, event)
local phase = event.phase
local touchID = event.id
if(phase == "began") then
elseif(phase == "moved") then
elseif(phase == "ended" or phase == "cancelled") then
if(m.menuActivator == 1) then
transition.to( menuFunction.menuBar, { x = m.menuInfo.x, y = h*.964, time = 200 } )
--transition.to( group, { x = 0, y = 0, time = 10 } )
m.menuActivator = 0
end
end
end
function scene:createScene( event )
local group = self.view
group:insert( menuFunction.menuBar ) -- *** ERROR occurs here
end
function scene:enterScene( event )
local group = self.view
end
function scene:exitScene( event )
local group = self.view
end
function scene:destroyScene( event )
local group = self.view
end
scene:addEventListener( "createScene", scene )
scene:addEventListener( "enterScene", scene )
scene:addEventListener( "exitScene", scene )
scene:addEventListener( "destroyScene", scene )
return scene
This is menuFunction.lua:
local m = require("myData")
local menu = require ("menu")
local w = display.contentWidth
local h = display.contentHeight
local menuFunction = {}
--menuBar
menuFunction.menuBar = display.newImage( "images/menuBar1.png")
menuFunction.menuBar.x = w*(1/2)
menuFunction.menuBar.y = h*1.465
menuFunction.menuBar.height = h
menuFunction.menuBar:setReferencePoint(display.TopLeftReferencePoint)
menuFunction.menuBar.touch = menu.menuSwipe
menuFunction.menuBar:addEventListener("touch", menuFunction.menuBar)
return menuFunction
This is the exact error message:
ERROR: table expected. If this is a function call, you might have used '.' instead of ':'
message**
Does this happen every time this code is called, or does it by any chance work the first time and then crashes? In your case, code could work the first time you enter the scene, but the second time you do, it may crash [if you remove scenes in between].
When you do a 'require' of a file, its contents are executed and returned value is saved in the global packages table. When you require the same file again, the returned value is taken from the global packages table instead, the code is not executed again.
So if you by any chance require this file in one spot of your app, and then call :removeSelf() and nil the reference of the menuBar, the display object will be removed and its reference will cease to exist, and calling the require again, will not recreate the object. Fully removing a scene will also remove the display objects.
So what you wanted to achieve is very sensible [contrary to what #Schollii says], but your "module" should allow creation of multiple objects if you want to get rid of them during runtime.
I'm not going to correct your code, just a simple example of how you can achieve this:
-- menu.lua
local menuCreator = {}
menuCreator.newMenu = function(params)
local menu = display.newGroup()
-- create your menu here
return menu
end
return menuCreator
Now anytime you do:
local menuCreator = require("menu.lua")
you will be able to call:
local menu = menuCreator.newMenu(someParams)
and get yourself a nice new menu wherever you need.
If it's not shown all the time on screen, it may be better to create a new one whenever you need it, and then remove it from the memory.
There are several issues with this, and none of them seem related to your error but fixing them will either also fix the error or make the cause of the error more obvious. Please fix following and update:
Although Lua allows it, don't use circular includes, where A includes B which includes A. Instead have menu require menuFunction and then call a creation function in menuFuntion:
-- menuFunction.lua
local m = require("myData")
-- require("menu") -- BAD! :)
local w = display.contentWidth
local h = display.contentHeight
local menuBar = display.newImage( "images/menuBar1.png")
menuBar.x = w*(1/2)
menuBar.y = h*1.465
menuBar.height = h
menuBar:setReferencePoint(display.TopLeftReferencePoint)
local menuFunction = { menuBar = menuBar }
function createMenuBar(menuSwipe)
menuFunction.menuBar.touch = menuSwipe
menuFunction.menuBar:addEventListener("touch", menuFunction.menuBar)
return menuFunction
end
-- menu.lua
function createScene(event)
local mf = require('menuFunction')
mfFunction = mf.createMenuBar(menuSwipe)
group:insert(menuFunction.menuBar)
end
Secondly out of the four calls to group:insert() the first 3 refer to objects that are not shown in the code and don't see relevant to problem, they should be removed or if you think relevant, comment why their code now shown, or show their code.

Delete object[i] from table or group in corona sdk

i have a problem (obviusly :P)
i'm create a mini game, and when i touch a Object-A , creates an Object-B.
If i touch N times, this create N Object-B.
(Object-B are Bubbles in my game)
so, i try when I touch the bubble (object-B), that disappears or perform any actions.
I try adding Object-B to Array
local t = {}
.
.
.
bur = display.newImage("burbuja.png")
table.insert(t,bur)
and where i have my eventListeners i wrote:
for i=1, #t do
bur[i]:addEventListener("tap",reventar(i))
end
and my function 'reventar'
local function reventar (event,id)
table.remove(t,id)
end
i'm lost, and only i want disappears the bubbles.
you're probably gonna want to do something like this:
local t = {}
bur = display.newImage("burbuja.png")
table.insert(t,bur)
-- declaring the function first so it can be used later in the for loop
local function reventar(event)
t[event.target.id] = nil -- We remove object from table
event.target:removeSelf() -- Also remember to remove from display
end
for i=1,#t do
t[i].id = i
t[i]:addEventListener("tap", reventar)
end
Hope this helps.
EDIT
I would do it this way, because it's better when you want to loop through the objects:
local t = {}
-- declaring the function first so it can be used later
local function reventar(event)
event.target.kill = true -- Mark the clicked object for later destruction
end
bur = display.newImage("burbuja.png")
bur:addEventListener("tap", reventar)
table.insert(t,bur)
local function loop(event)
for i = #t, 1, -1 do
local object = t[i]
-- Do stuff to object here, such as object.y = object.y + 1
if object.kill then -- Check if object is marked for destruction
local child = table.remove(t, i) -- Remove from table
if child ~= nil then
-- Remove from display and nil it
child:removeSelf()
child = nil
end
end
end
end
Runtime:addEventListener("enterFrame", loop) -- Remember to remove this when no longer needed

Resources