这里仅仅介绍extern.lua的当中的两个方法,也是我们接下来要用到的两个方法。
1.function class(classname, super) 这种方法用于声明一个类,第一个參数是你要定义的类名,第二个參数要继承的父类实体(从參数中能够发现仅仅是实现单继承)。
2.function clone(Object) 这种方法用于复制对象
回到正题,想要增添敌机,第一件事想到肯定是定义一个敌机的实体类,那我们定义一个吧,在EnemyLayer.lua文件里定义Enemy实体类
require "Lua/extern" Enemy = class("Enemy", function(frame) local sprite = CCSprite:createWithSpriteFrameName(frame) local peer = {} tolua.setpeer(sprite,peer) return sprite end ) Enemy.__index = Enemy function Enemy:create(frame,life,score,level) local enemy = Enemy.new(frame) local peer = tolua.getpeer(enemy) peer.life = life--敌机的生命值 peer.score = score--打爆这架敌机,可获得的分数 peer.level = level--敌机的等级,图片资源中有三种敌机 return enemy end function Enemy:getLife() return tolua.getpeer(self).life end function Enemy:getLevel() return tolua.getpeer(self).level end function Enemy:getScore() return tolua.getpeer(self).score end function Enemy:loseLife() tolua.getpeer(self).life = tolua.getpeer(self).life - 1 end
有了敌机,我们再创建一个敌机图层
function create() layer = CCLayer:create() start() return layer end
start()方法将全部敌机加入到图层中
local enemyAEntry = nil local enemyBEntry = nil local enemyCEntry = nil function start() enemyAEntry = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(addEnemyA, 3,false) enemyBEntry = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(addEnemyB, 1,false) enemyCEntry = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(addEnemyC, 10,false) end
在这儿就仅仅贴出加入敌机A方法的代码addEnemyA(),其它两个都与这个类似。
local Enemy_A_Life = 1 local Enemy_B_Life = 2 local Enemy_C_Life = 3 local Enemy_A_SCORE = 5 local Enemy_B_SCORE = 10 local Enemy_C_SCORE = 15 local Enemy_A_Level = 1 local Enemy_B_Level = 2 local Enemy_C_Level = 3 local layer = nil local enemyArray = {} function addEnemyAB(frameName,life,score,level) local enemy = Enemy:create(frameName,life,score,level) local enemyASizie = enemy:getContentSize() local minX = enemyASizie.width / 2 local maxX = visibleSize.width - (enemyASizie.width / 2) local rangX = maxX - minX local actualX = (math.random() * rangX) + minX enemy:setPosition(ccp(actualX,visibleSize.height + enemyASizie.height / 2)) layer:addChild(enemy) table.insert(enemyArray,enemy) local minDuration = 10 local maxDuration = 20 local rangeDur = maxDuration - minDuration local actuakDur = (math.random() * rangeDur) + minDuration local actionMove = CCMoveTo:create(actuakDur,ccp(actualX,0 - enemy:getContentSize().height / 2)) local actionDone = CCCallFuncN:create(removeEnemy) local sequence = CCSequence:createWithTwoActions(actionMove,actionDone) enemy:runAction(sequence) end function addEnemyA() addEnemyAB("enemy1.png",Enemy_A_Life,Enemy_A_SCORE,Enemy_A_Level) end
enemyArray这个參数用来存放全部的敌机,在后面的碰撞检測时会实用处。
本计划将代码整理后再上传,无赖这段时间太忙,没时间整理,也不知道什么时候有时间更新博文。
所以今天先将全部代码上传一份吧。方便大家学习交流。
源代码下载http://download.csdn.net/detail/yifuteli/7305869