事件监听器从外部模块调用函数

时间:2013-02-02 14:32:19

标签: module corona addeventlistener

因为标题声明我有一个事件监听器,它从我的火箭类中调用一个函数

但是我在调​​用上面的代码函数时收到错误。

ROCKETCLASS.LUA

module(..., package.seeall)

function rocket()

local rocket = {}
local rocket_mt = { __index = rocket }  -- metatable
local sprite
local rockettop, rocketbottom, speedX, speedY


function rocket.new()   -- constructor

local newRocket = {
sprite = "red-rocket.png"

}
return setmetatable( newRocket, rocket_mt )
end 

function rocket:draw(x,y,group)

local spritesheetdata = {
width = 30,
height = 55,
numFrames = 7,
sheetContentWidth = 210,
sheetContentHeight = 55,
}


local spritesheet = graphics.newImageSheet( "red_rocket.png", spritesheetdata )



local spritesequencedata = {

 { name = "idle", frames = {1}, 
   } ,

 { name = "afterburn",
   start = 2,
   count = 2,
   time = 500,
   loopCount = 0, -- optional default 0(infinite)
   loopDirection = "forward" -- optional (default)
   } ,
   {  name = "explode",
   start = 4,
   count = 4,
   time = 1200,
   loopCount = 1
     }
 }

   sprite = display.newSprite( spritesheet, spritesequencedata)
   rockettop = {-14.5, 5, 0, -25,14.5,5}
   rocketbottom = {-14.5,7,-14.5,6,14.5,6,14.5,7}


   physics.addBody(sprite, {shape = rockettop},{bounce = 0.5,friction = 0.6, shape =  rocketbottom} )
   sprite.angularDamping = 2
   sprite.x = x
   sprite.y = y
   sprite:setSequence("idle")
   sprite:play()
   group:insert (sprite)

   end

function rocket:thrust(event)

speedX = 0.0025 * (math.sin(sprite.rotation*(math.pi/180)))
speedY = -0.0025 * (math.cos(sprite.rotation*(math.pi/180)))
if(event.phase =="began") then

  sprite:applyLinearImpulse(speedX, speedY, sprite.x, sprite.y)

  return true
  end
  sprite:setSequence("afterburn")
  sprite:play()

end

   return rocket


 end

和CONTROLS.LUA

module(..., package.seeall)
rocket = require("rocketclass")



local controlthrust = display.newImage("thrust control.png")
controlthrust.y = display.contentWidth/1.6   
controlthrust.x = display.contentWidth/1.1


local controlleft = display.newImage("direction controls.png")
controlleft.y = display.contentWidth/1.6

local controlright = display.newImage("direction controls.png")
controlright.y = display.contentWidth/1.6
controlright.x = display.contentWidth/6
controlright.rotation = 180



controlthrust:addEventListener("touch",rocket:thrust)

来自控制台收到的错误是:

controls.lua:21:尝试调用方法'推力' 堆栈追溯: C:在功能'错误' ?:在函数'gotoScene'中 ... nts \ corona projects \ rocket lander - classes \ menu.lu

1 个答案:

答案 0 :(得分:0)

我看不到你在哪里调用rocket.new()。我认为你需要做这样的事情:

 rocketclass = require("rocketclass")

 rocket = rocketclass.new()
在为它设置触摸处理程序之前