i've been stuck on this for a while now and really need help. Basically what I'm trying to do is have these objects spawn on screen and then allow the player to drag them around as they want.
At the moment the random objects flow onto screen, however when I try to click on 'star1' I get the error :
Attempt to index local 'star1' (a nil value) How should I do this properly?
Here is my code:
display.setStatusBar(display.HiddenStatusBar)
local physics = require('physics')
physics.start()
--physics.setGravity(0, 0)
_W = display.contentWidth; --Returns Screen Width
_H = display.contentHeight; --Returns Screen Height
local bg = display.newImage('bg1.png')
local starTable = {}
ship = display.newImage("head.png")
ship.name = "ship"
ship.x = -80
ship.y = 100
physics.addBody(ship, { isSensor = true })
ship.bodyType = 'dynamic'
shipIntro = transition.to(ship,{time=4000, x=200})
ship.width = 40
ship.height = 40
ship.gravityScale = 0
local star1 = display.newImage("acorn")
star1.name = "star1"
physics.addBody(star1, { isSensor = true })
star1.bodyType = 'static'
function initStar()
local star1 = {}
star1.imgpath = "acorn.png"
star1.movementSpeed = 10000
table.insert(starTable, star1)
local star2 = {}
star2.imgpath = "enemyA.png"
star2.movementSpeed = 12000
table.insert(starTable, star2);
local star3 = {}
star3.imgpath = "star3.png"
star3.movementSpeed = 14000
table.insert(starTable, star3)
end
function getRandomStar()
local temp = starTable[math.random(1, #starTable)]
local randomStar = display.newImage(temp.imgpath)
randomStar.myName = "star"
randomStar.movementSpeed = temp.movementSpeed
randomStar.x = math.random(0,_W)
randomStar.y = _H + 50 -- Start the star off screen
randomStar.rotation = math.random(0,360)
starMove = transition.to(randomStar, {
time=randomStar.movementSpeed,
y=-45,
onComplete = function(self) self.parent:remove(self); self = nil; end
}) -- Move the star
end
function star1:touch( event )
if event.phase == "began" then
self.markX = self.x
self.markY = self.y
elseif event.phase == "moved" then
local x = (event.x - event.xStart) + self.markX
local y = (event.y - event.yStart) + self.markY
self.x, self.y = x, y -- move object based on calculations above
end
return true
end
star1:addEventListener( "touch", star1 )
starTimer1 = timer.performWithDelay(1700,getRandomStar, 0)
starTimer2 = timer.performWithDelay(2300,getRandomStar, 0)
starTimer3 = timer.performWithDelay(2700,getRandomStar, 0)
initStar()
star1
with the same name. An error-prone style of coding. – Egor Skriptunoff