MainScene里用定时器时一直报attempt to call method 'Update' (a nil value) stack traceback:
我的cocos2dx版本是3.1.0、VS2013的,与老师的定时器写法一样的,也调试了多次,当运行截图的注释部分时蛇是可以移动的,就是用定时器就访问不了update了,这个怎么解决啊?困了我两天
MainScene.lua代码:
local MainScene = class("MainScene", cc.load("mvc").ViewBase)
local Snake = require "app.views.Snake";
--MainScene.RESOURCE_FILENAME = "MainScene.csb"
local cMoveSpeen = 0.3;
function MainScene:onEnter()
self.snake = Snake.new(self)
--self.snake:Update()
--self.snake:Update()
--self.snake:Update()
--self.snake:Update()
local tick = function()
self.snake:Update()
end;
cc.Director:getInstance():getScheduler():scheduleScriptFunc(tick,cMoveSpeen,false);
end
return MainScene
Snake.lua代码:
local Snake = class("Snake",cc.load("mvc").ViewBase);
local Body = require "app.views.Body";
local cInitLen = 3;
function Snake:ctor(node)
self.BodyArray = {}
self.node = node
self.MoveDir = "left"
for i = 1,cInitLen do
self:Grow(i == 1)
end
end
function Snake:GetTailGrid()
if #self.BodyArray == 0 then
return 0,0
end
local tail = self.BodyArray[#self.BodyArray];
return tail.X,tail.Y
end
function Snake:Grow(isHead)
local tailX,tailY = self:GetTailGrid();
local body = Body.new(self,tailX,tailY,self.node,isHead);
table.insert(self.BodyArray,body)
end
local function OffsetGridByDir(x,y,dir)
if dir == "left" then
return x-1,y
elseif dir == "right" then
return x+1,y
elseif dir == "up" then
return x,y-1
elseif dir == "down" then
return x,y+1
end
print("Unkown dir", dir)
return x,y
end;
function Snake:Update()
if #self.BodyArray == 0 then
return
end
for i = #self.BodyArray,1,-1 do
local body = self.BodyArray[i];
if i == 1 then
body.X,body.Y = OffsetGridByDir(body.X,body.Y,self.MoveDir)
else
local front = self.BodyArray[i-1];
body.X,body.Y = front.X,front.Y
end
body:Update()
end
end
return Snake