How to remove all objects with the same name - lua

Hi how can i remove all objects with the same name, if i use:
local screenGroup = self.view
local randomBad3 = function()
badC3 = display.newImage("BCloud3-"..tostring(math.random(1, 12))..".png")
badC3.x = math.random (0, 450); badC3.y = -50-- -50
physics.addBody( badC3, { density=.3, bounce=0.3, friction=.3, radius=25, filter=badc3CollisionFilter } )
badC3.name = "BCloud3"
badC3.isSensor = true
badC3.rotation = math.random(-30,30) -- Rotate the object
trans5 = transition.to( badC3, { time= math.random(yForB3A, yForB3B), y=600, transition=easing.OutExpo } )
badC3.gravityScale = 0.0
local cleanup
cleanup = function()
if badC3 then
if badC3.y >590 then
badC3:removeSelf()
badC3 = nil
end
end
end
Runtime:addEventListener("enterFrame", cleanup)
end
randomBadC3 = timer.performWithDelay( math.random(1000, 5000), randomBad3, 0 )
--
if badC3 then
badC3:removeSelf()
badC3 = nil
end
it only removes the last spawned one, not all of them

Add all images into one group when you want to delete delete entire group.
for i=1,#maingroup do
if maingroup[i] then
maingroup[i]:removeSelf();maingroup[i]=nil
end
end
end

Related

How to attach rope to player ragdoll and a player (effectively dragging a ragdoll via a rope) without the weird input lag?

I'm first going to start off with my code which is in a Server Script:
local an = Instance.new("Animation")
an.AnimationId = "rbxassetid://11699868187"
local idle = Instance.new("Animation")
idle.AnimationId = "rbxassetid://11699874417"
local ant
local idlet
local canthit = {}
local knockTime = 30
function takeOwnership(model)
for i, v in pairs(model:GetDescendants()) do
if v:IsA("Part") or v:IsA("BasePart") then
repeat
v:SetNetworkOwner(nil)
until v:GetNetworkOwner() == nil
end
end
end
function resetOwernship(model, ply)
for i, v in pairs(model:GetDescendants()) do
if v:IsA("Part") or v:IsA("BasePart") then
v:SetNetworkOwner(ply)
end
end
end
function rag(char)
local ah = Instance.new("IntValue")
ah.Parent = char
ah.Name = "MaxTime"
ah.Value = knockTime
local thib = Instance.new("IntValue")
thib.Parent = char
thib.Name = "Time"
thib.Value = knockTime
for i, v in pairs(char:GetDescendants()) do
if v:IsA("Motor6D") and v.Parent.Name ~= "HumanoidRootPart" then
local Socket = Instance.new("BallSocketConstraint")
local a1 = Instance.new("Attachment")
local a2 = Instance.new("Attachment")
a1.Parent = v.Part0
a2.Parent = v.Part1
Socket.Parent = v.Parent
Socket.Attachment0 = a1
Socket.Attachment1 = a2
a1.CFrame = v.C0
a2.CFrame = v.C1
Socket.LimitsEnabled = true
Socket.TwistLimitsEnabled = true
v:Destroy()
end
end
char.Humanoid.BreakJointsOnDeath = false
char.Humanoid.RequiresNeck = false
end
function unrag(char)
for i,v in pairs(char:GetDescendants()) do
if v:IsA("BallSocketConstraint") then
v.UpperAngle = 0
v.TwistUpperAngle = 0
v.TwistLowerAngle = 0
local Joints = Instance.new("Motor6D",v.Parent)
Joints.Part0 = v.Attachment0.Parent
Joints.Part1 = v.Attachment1.Parent
Joints.C0 = v.Attachment0.CFrame
Joints.C1 = v.Attachment1.CFrame
v:Destroy()
end
end
end
game:GetService("ReplicatedStorage").Jump.OnServerEvent:Connect(function(ply)
if ply.Character and ply.Team == game:GetService("Teams").Survivor then
if ply.Character.Ragdoll.Value == true then
--game:GetService("ReplicatedStorage"):WaitForChild("Message"):FireClient(ply, "Sorry, jumping isn't available for ragdolls right now")
end
end
end)
game.Players.PlayerAdded:Connect(function(p)
if #game:GetService("Teams").Beast:GetPlayers() == 1 then
p.Team = game:GetService("Teams").Survivor
else
p.Team = game:GetService("Teams").Beast
end
p.CharacterAdded:Connect(function(c)
canthit[p] = nil
if p.Team == game:GetService("Teams").Beast then
local theBat = game:GetService("ServerStorage").Bat:Clone()
theBat.Parent = c
theBat.Equipped:Connect(function()
local h = c:FindFirstChild("Humanoid")
if h then
local a = h:FindFirstChild("Animator")
if a then
idlet = a:LoadAnimation(idle)
idlet:Play()
end
end
end)
theBat.Activated:Connect(function()
local h = c:FindFirstChild("Humanoid")
if h then
local a = h:FindFirstChild("Animator")
if a then
ant = a:LoadAnimation(an)
ant:Play()
theBat.Handle.Swoosh:Play()
local thinge = theBat.Handle.Touched:Connect(function(t)
local ply = game.Players:GetPlayerFromCharacter(t:FindFirstAncestorWhichIsA("Model"))
local ragd = ply.Character:FindFirstChild("Ragdoll")
if ragd then
if ragd.Value == true then
return
end
end
if ply and ply.Team == game:GetService("Teams").Survivor and ply ~= p and not canthit[ply] then
theBat.Handle.Hit:Play()
canthit[ply] = true
local char = ply.Character
ragd.Value = true
rag(char)
while not (char.Time.Value <= 0) do
takeOwnership(char)
char.Humanoid:ChangeState(Enum.HumanoidStateType.Physics)
wait(1)
char.Time.Value -= 1
char.HP.Value -= .5
end
if char.HP.Value <= 0 then
char.HP.Value = 0
game:GetService("ReplicatedStorage"):WaitForChild("Message"):FireAllClients(ply.Name.." has been captured!")
char.Humanoid.Health = 0
return
end
char.Time:Destroy()
char.MaxTime:Destroy()
char.Humanoid:ChangeState(Enum.HumanoidStateType.GettingUp)
unrag(char)
resetOwernship(char, ply)
ragd.Value = false
coroutine.wrap(function()
wait(5)
canthit[ply] = nil
end)()
end
end)
wait(.2)
thinge:Disconnect()
end
end
end)
theBat.Unequipped:Connect(function()
if idlet then
idlet:Stop()
end
end)
end
end)
end)
So, this is my horrible code for a little game I am making. It's kind of similar to Flee the Facility. In my game, the person who is the 'beast' should be able to drag a player when they are knocked out, but they can't. I tried adding a rope constraint to the ragdoll and the 'beast', but it just makes the beast have input lag and makes it's animations go weird.
I must note that the beast is a random player. I would try setting ownership of the ragdoll'd player to the grabber (which is the 'beast') but I need to set it to the server in order to change the state to Physics. I would use an event and a local script but I do not want this to be exploitable at all.
So, my question is: How do I attach a rope from a player to a ragdolled player without the non-ragdolled player lagging or having weird input lag and weird animations?
Like I said, I tried setting ownership but that wouldn't work as I need server ownership for setting the humanoid's state to physics. Just using takeOwnership() then ChangeState both on the same line wouldn't work so I had to put it in the while loop.

How to also pause physics object before entering screen in corona?

I used physics.pause() and physics.start() , it works but my problem is that one function keeps displaying an object at the bottom and when I resume the game, those object are compiled and all of them enter screen at once. I hope someone can help me.
here's my code:
local isPaused = false
function pausePhysics( event )
if "began" == event.phase then
if isPaused == false then
physics.pause(lobo)
isPaused = true
timer.pause(countDownTimer)
local decide = display.newImage("wood.png")
decide.x = display.contentWidth*0.5
decide.y = display.contentHeight*0.5
local yes
local no
local function oo()
if score == 0 then
onBackBtnRelease()
elseif score >0 and score <=10 then
GameOver1()
elseif score >10 and score <=20 then
GameOver2()
else
GameOver3()
end
end
yes = widget.newButton
{
defaultFile= "yes.png",
width=100, height=50,
onRelease = oo
}
yes.x = display.contentWidth*0.3
yes.y = display.contentHeight - 200
local function hindi()
if isPaused == true then
physics.start()
isPaused = false
timer.resume(countDownTimer)
display.remove(decide)
decide = nil
display.remove(yes)
yes = nil
display.remove(no)
no = nil
end
return true
end
no = widget.newButton
{
defaultFile= "no.png",
width=100, height=50,
onRelease = hindi
}
no.x = display.contentWidth*0.7
no.y = display.contentHeight - 200
sceneGroup:insert(decide)
sceneGroup:insert(yes)
sceneGroup:insert(no)
return true
end
end
end
local function tapos(event)
if (event.phase == "began") then
physics.addBody(backBtn, "static")
end
end
Runtime:addEventListener("enterFrame", backBtn)
backBtn:addEventListener("touch", pausePhysics)
local function ulit()
local mRandom = math.random
local balloon = { ("blue.png"), ("green.png"), ("red.png"), ("orange.png"), ("pink.png"), ("violet.png"), ("yellow.png"), ("blue2.png"), ("green2.png"), ("red2.png"), ("orange2.png"), ("pink2.png"), ("violet2.png"), ("yellow2.png") }
local lobo = display.newImage( balloon[mRandom(10)], mRandom(30,270), mRandom(550,650) )
physics.addBody( lobo, { density=0.1, friction=2.0, bounce=0.0, velocity=-40, isSensor=true } );
end
timer.performWithDelay(300,ulit,0)

removeSelf() a nil value error

Hi for some reason corona is giving me this error: attempt to index global 'backC' (a nil value)
local randomBackC = function()
backC = display.newImage("Cloud"..tostring(math.random(1, 4))..".png")
backC.x = math.random (30, 450); backC.y = -20
physics.addBody( backC, { density=2.9, friction=0.5, bounce=0.7, radius=24 } )
end
timer.performWithDelay( 500, randomBackC, 0 )
end
local function cleanup()
if backC.y >100 then
backC:removeSelf()
end
end
Runtime:addEventListener("enterFrame", cleanup)
any ideas of what is causing this?
backC may be already removed because of the Runtime:addEventListener("enterFrame", cleanup)
enterFrame will call the cleanup() over and over again, so you have to remove the enterFrame after you remove the backC and if you want to create multiple objects, make it local only to the function because it may cause referencing problem.
Like this
local randomBackC = function()
local backC = display.newImage("Cloud"..tostring(math.random(1, 4))..".png")
backC.x = math.random (30, 450); backC.y = -20
physics.addBody( backC, { density=2.9, friction=0.5, bounce=0.7, radius=24 } )
local cleanup
cleanup = function()
if backC then
if backC.y >100 then
backC:removeSelf()
backC = nil
Runtime:removeEventListener("enterFrame", cleanup)
end
end
end
Runtime:addEventListener("enterFrame", cleanup)
end
timer.performWithDelay( 500, randomBackC, 0 )

spawning objects not removing after leaving scene

Hi my objects are not removing after leaving the scene, i have tried to purging and removing the scene, but the objects will just keep on spawning in a other scene?
local badclout1 = {}
local bad1Group = display.newGroup()
local function spawnBC1()
local badclouts1 = display.newImage("BCloud1.png")
badclouts1.x = math.random(0, _W)
physics.addBody( badclouts1, "dynamic", { density=.1, bounce=.1, friction=.2, radius=45 } )
badclouts1.name = "BCloud1"
badclouts1.bodyType = "kinematic"
badclouts1.isSensor = true
badclouts1.y = math.random(-100, -50)
badclouts1.index = #badclout1 + 1
bad1Group:insert(badclouts1)
badclouts1.rotation = math.random(-10,10) -- Rotate the object
badclouts1:setLinearVelocity(0, math.random(speeda1, speedb1)) -- Drop down
badclout1[badclouts1.index] = badclouts1
tmrSpawn1 = timer.performWithDelay(math.random(spawna, spawnb), spawnBC1)
return badclouts1
end
tmrSpawn1 = timer.performWithDelay(math.random(1000, 10000), spawnBC1)
local function removeBomb()
for i, v in pairs(badclout1) do
if badclout1[i].y >1000 then
badclout1[i]:removeSelf()
badclout1[i] = nil
end
end
end
Runtime:addEventListener("enterFrame", removeBomb)
is there something in my code that keeps it on the screen ?
You need to cancel your performWithDelay function using timer.cancel(tmrSpawn1). Because you're calling it recursively, it will just keep going until you cancel it.

Changing Scenes in Corona objects stay on screen

I have been modifying code from the memory match game to use scenes, sounds, and a 2d table. Adding the scenes has been the hard part. I have it set up to randomly select items from my 2d table. Load those into a temporary table, shuffle them shuffle(), then boardSet(); to load their sounds and place them on the screen. Basically after the game is over I want the scene to reload or go back to the menu to start again. Selecting random data{} elements over and over.
I have tried returning to the menu, or going to a duplicate scene however I can't seem to correctly unload the objects created by my 2d array, as I can't properly add each item into a display group. I have tried everything I can think of. Right now my game loop is setup to add the play again btn that I want to restart the game after one match is found.
This link was a start in the right direction I believe with information about dealing with tables and groups. I still don't know how to cycle thru my 2d table to include everything in a group and then properly unload it.
http://developer.coronalabs.com/content/application-programming-guide-graphics-and-drawing#Variable_References
---------------------------------------------------------------------------------
--
-- level1.lua
--
---------------------------------------------------------------------------------
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local widget = require "widget"
---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
local image, text1, text2, text3, memTimer
-- forward declarations and other locals
local againBtn
-- 'onRelease' event listener for playBtn
local function onPlayBtnRelease()
-- go to level1.lua scene
storyboard.gotoScene( "menu", "fade", 500 )
return true -- indicates successful touch
end
-- Preload the sound file (needed for Android)
--
local playBeep = function( testSound )
media.playEventSound( testSound )
end
---Preload sounds
ki = audio.loadSound("ki-nawaneyoo.mp3")
u = audio.loadSound("u.mp3")
mayuhoo = audio.loadSound("mayuhoo.mp3")
--End Sound Test
--Set Global width and height variables
_W = display.contentWidth;
_H = display.contentHeight;
---Count number of correct matches
local matchCount = 0;
--Hide status bar
display.setStatusBar(display.HiddenStatusBar);
--Declare a totalButtons variable to track number of buttons on screen
local totalButtons = 0
--Declare variable to track button select
local secondSelect = 0
local checkForMatch = false
--Declare Data Table
local data = {}
--Load objects into data
data[1] = {}
data[1].title = "Naka"
data[1].subtitle = "a"
data[1].image = "a.png"
data[1].image1 = "ear.png"
data[1].sound = "naka-ear.caf"
data[1].sound1 = "naka-ear.mp3"
data[2] = {}
data[2].title = "Aapuhu"
data[2].subtitle = "aa"
data[2].image = "aa.png"
data[2].image1 = "eyebrow.png"
data[2].sound = "aapuhu-eyebrow.caf"
data[2].sound1 = "aapuhu-eyebrow.mp3"
data[3] = {}
data[3].title = "Ego"
data[3].subtitle = "Ego"
data[3].image = "e.png"
data[3].image1 = "tongue.png"
data[3].sound = "ego-tongue.caf"
data[3].sound1 = "ego-tongue.mp3"
data[4] = {}
data[4].title = "Kamoo"
data[4].subtitle = "kamoo"
data[4].image = "ee.png"
data[4].image1 = "chin.png"
data[4].sound = "kamoo-chin.caf"
data[4].sound1 = "kamoo-chin.mp3"
data[5] = {}
data[5].title = "Kowpa"
data[5].subtitle = "ego"
data[5].image = "leg.png"
data[5].image1 = "leg.png"
data[5].sound = "kowpa-leg.caf"
data[5].sound1 = "kowpa-leg.mp3"
data[6] = {}
data[6].title = "Mae"
data[6].subtitle = "kwa"
data[6].image = "hand.png"
data[6].image1 = "hand.png"
data[6].sound = "mae-hand.caf"
data[6].sound1 = "mae-hand.mp3"
data[7] = {}
data[7].title = "Nodo"
data[7].subtitle = "kwe"
data[7].image = "kwe.png"
data[7].image1 = "throat.png"
data[7].sound = "nodo-throat.caf"
data[7].sound1 = "nodo-throat.mp3"
data[8] = {}
data[8].title = "Matogo"
data[8].subtitle = "kwe"
data[8].image = "kwe.png"
data[8].image1 = "thumb.png"
data[8].sound = "matogo-thumb.caf"
data[8].sound1 = "matogo-thumb.mp3"
data[9] = {}
data[9].title = "Matzehe"
data[9].subtitle = "kwe"
data[9].image = "kwe.png"
data[9].image1 = "elbow.png"
data[9].sound = "matzehe-eblow.caf"
data[9].sound1 = "matzehe-elbow.mp3"
data[10] = {}
data[10].title = "Kuku"
data[10].subtitle = "kwe"
data[10].image = "kwe.png"
data[10].image1 = "foot.png"
data[10].sound = "kuku-foot.caf"
data[10].sound1 = "kuku-foot.mp3"
--Declare button, buttonCover, and buttonImages table
local tableCopy = {}
local buttonImages = {}
--Shuffle data table
--local shuffleSet = function()
--Shuffle data table
math.randomseed (os.time())
local function shuffle(a)
local n = #a
local t
local k
while(n > 0) do
t = a[n]
k = math.random(n)
a[n] = a[k]
a[k] = t
n = n - 1
end
return a
end
local tableCopy = shuffle(data);
local button = {}
local buttonCover = {}
--Choose six random objects from data to be used in game.
local firstSix = {}
for i = 1,6 do
firstSix[i] = tableCopy[i];
end
local buttonImages = {firstSix[1],firstSix[1],firstSix[2],firstSix[2],firstSix[3],firstSix[3],firstSix[4],firstSix[4],firstSix[5],firstSix[5],firstSix[6],firstSix[6]}
--end
--Declare and prime a last button selected variable
local lastButton;-- = display.newImage("1.png");
--lastButton.myName = 1;
--
--Set up simple off-white background
--Notify player if match is found or not
local matchText = display.newText(" ", 0, 0, native.systemFont, 65)
matchText:setReferencePoint(display.CenterReferencePoint)
matchText:setTextColor(255, 255, 255)
matchText.x = _W/2
--
--Set starting point for button grid
local x = -20
local matchesFound = 0;
--Set up game function
local function game(object, event)
if(event.phase == "began") then
if(checkForMatch == false and secondSelect == 0) then
--Flip over first button
buttonCover[object.number].isVisible = false;
audio.play(object.sound);
lastButton = object
checkForMatch = true
elseif(checkForMatch == true and object.number ~= lastButton.number) then
if(secondSelect == 0) then
--Flip over second button
buttonCover[object.number].isVisible = false;
secondSelect = 1;
--If buttons do not match, flip buttons over
if(lastButton.myName ~= object.myName) then
audio.play(object.sound);
timer.performWithDelay(1000,function()
matchText.text = "Ki Nawa'neyoo";
audio.play(ki); end,1)
timer.performWithDelay(2500, function()
matchText.text = " ";
checkForMatch = false;
secondSelect = 0;
buttonCover[lastButton.number].isVisible = true;
buttonCover[object.number].isVisible = true;
end, 1)
--If buttons DO match, remove buttons
elseif(lastButton.myName == object.myName) then
matchText.text = "U " .. object.myName .. " Mayuhoo";
audio.play(u)
timer.performWithDelay(750,function()
audio.play(object.sound); end, 1)
timer.performWithDelay(1500,function()
audio.play(mayuhoo); end, 1)
timer.performWithDelay(2400, function()
matchText.text = " ";
checkForMatch = false;
secondSelect = 0;
lastButton:removeSelf();
object:removeSelf();
buttonCover[lastButton.number]:removeSelf();
buttonCover[object.number]:removeSelf();
matchesFound = matchesFound + 1;
timer.performWithDelay(250, function()
if (matchesFound == 1) then
matchText.text = " Play Again? ";
againBtn.isVisible = true;
-- all display objects must be inserted into group
--group:insert( playBtn )
end
end, 1)
end, 1)
end
end
end
end
end
--]]
-- Touch event listener for background image
--[[
local function onSceneTouch( self, event )
if event.phase == "began" then
storyboard.gotoScene( "scene2", "slideLeft", 800 )
return true
end
end
--]]
-- Called when the scene's view does not exist:
function scene:createScene( event )
local screenGroup = self.view
local image = display.newImageRect( "bg.png", display.contentWidth, display.contentHeight )
image:setReferencePoint( display.TopLeftReferencePoint )
image.x, image.y = 0, 0
screenGroup:insert( image )
local function boardSet()
for count = 1,3 do
x = x + 100 * 2
y = 20 *2
for insideCount = 1,4 do
y = y + 90 * 2
--Assign each image a random location on grid
local temp = math.random(1,#buttonImages)
button[count] = display.newImageRect(buttonImages[temp].image1, 150, 150);
--Position the button
button[count].x = x;
button[count].y = y;
--Give each a button a name
button[count].myName = buttonImages[temp].title
-- Preload the sound file (needed for Android)
--Give each button a sounds
soundID = audio.loadSound(buttonImages[temp].sound1)
button[count].sound = soundID
button[count].sound1 = soundID
button[count].number = totalButtons
--Remove button from buttonImages table
table.remove(buttonImages, temp)
--Set a cover to hide the button image
buttonCover[totalButtons] = display.newImageRect("button.png", 150, 150);
buttonCover[totalButtons].x = x; buttonCover[totalButtons].y = y;
--screenGroup:insert(button[count].)
totalButtons = totalButtons + 1
--Attach listener event to each button
button[count].touch = game
button[count]:addEventListener( "touch", button[count] )
end
end
end
boardSet();
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
againBtn = widget.newButton{
label="Play Again?",
fontSize = 25,
labelColor = { default={255}, over={128} },
default="button1.png",
over="button-over.png",
width=250, height=100,
onRelease = onPlayBtnRelease -- event listener function
}
againBtn:setReferencePoint( display.CenterReferencePoint )
againBtn.x = display.contentWidth * 0.5
againBtn.y = display.contentHeight - 125
againBtn.isVisible = false
print( "1: enterScene event" )
-- remove previous scene's view
end
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
print( "1: exitScene event" )
if againBtn then
matchText.text = " "
againBtn:removeSelf() -- widgets must be manually removed
button = nil
buttonCover = nil
firstSix = nil
data = nil
tableCopy = nil
buttonImages = nil
againBtn = nil
end
end
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
local screenGroup = self.view
storyboard.removeScene();
--storyboard.purgeScene( "level1" )
print( "((destroying scene 1's view))" )
end
---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
---------------------------------------------------------------------------------
return scene
Yeah, this is simple.
here is an example(assuming that you have implemented storyboard)
function scene:createScene(event)
screenGroup = self.view
local image = display.newImage("image.png")
screenGroup:insert(image)
end
Now everything will go fine :)
Add all the display objects to a group.local myGroup = display.newGroup();
local img = display.newImage("yourimage.png");
myGroup:insert(img);
For example
If you follow this method, all display objects will not be flushed out of memory when you change the screen.
When using corona storyboard you need to add display objects to the group. For example you would need to add all of your display objects into screenGroup in order for them to be removed when you change scenes.

Resources