蛇不动 身和头重叠,求解..

来源:4-1 蛇身

流年6

2016-02-13 15:00

蛇不动,蛇身和头重叠在中央不动,代码应该和视频里的一样,不知怎么破,请教老师求解

mainscene.lua:

local Snake = require"app.Snake"


local MainScene = class("MainScene", function()

    return display.newScene("MainScene")

end)


--[[function MainScene:ctor()

    cc.ui.UILabel.new({

            UILabelType = 2, text = "Hello, World", size = 64})

        :align(display.CENTER, display.cx, display.cy)

        :addTo(self)

end]]--



local cMoveSpeed = 0.3



function MainScene:onEnter()

 self.snake = Snake.new(self)

 

  local tick = function()

   self.snake:Update()

  end

  

 cc.Director:getInstance():getScheduler():scheduleScriptFunc(tick,cMoveSpeed,false)

 

 

 

 

end


function MainScene:onExit()

end


return MainScene



Snake.lua:

local Snake = class("Snake")

local Body = require("app.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 tailX,tailY

 

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("unknown dir",dir)

 

 return x,y

 

end


function Snake:Update()


 if#self.BodyArray == 0 then

  return 

 end

 

 

 --YXXX

 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

蛇就是不动!!

写回答 关注

1回答

  • 且听丶风吟
    2016-03-17 14:56:56

    function Snake:GetTailGrid()返回值tailX,tailY应该是tail.X,tail.Y

Cocos2d-x游戏开发之贪吃蛇(上)

贪吃蛇都玩过~有没有想过自己实现呢,一起学习来吧

32438 学习 · 122 问题

查看课程

相似问题