Cocos2d-X 3.2 lua语言飞机大战开发实例(二)
1. 敌机类的封装以及碰撞检测
--
Enemy的类中
require "Cocos2d"
local Enemy=class("Enemy",function ()
return cc.Node:create()
end)
function Enemy:create(t,x,y)
local enemy=Enemy.new()
enemy:addChild(enemy:init(t,x,y))
return enemy
end
--构造
function Enemy:ctor()
self.winsize=cc.Director:getInstance():getWinSize()
self.ex=0
self.ey=0
self.type=0
self.dirH=true --真为rigth 假为left
self.dirV=true --false up true down
self.flyWidth=30 --摇摆的幅度
self.flyX=0 --当前的摇摆值
self.count=0 --控制移动的逻辑执行的次数
end
--init()
function Enemy:init(t,x,y)
local layer=cc.Layer:create()
local sp=cc.Sprite:create()
layer:addChild(sp)
--敌机动画
if t==0 then
--动画的每一帧
local sf1=cc.SpriteFrame:create("fonts/Resources/ld1.png",cc.rect(0,0,87,100))
local sf2=cc.SpriteFrame:create("fonts/Resources/ld1.png",cc.rect(87,0,87,100))
local allf={ sf1,sf2}
--创建动画
local animation=cc.Animation:createWithSpriteFrames(allf,0.1)
local animate=cc.Animate:create(animation)
sp:runAction(cc.RepeatForever:create(animate))
elseif t==1 then
local sf1=cc.SpriteFrame:create("fonts/Resources/ld1.png",cc.rect(0,0,87,100))
local sf2=cc.SpriteFrame:create("fonts/Resources/ld1.png",cc.rect(87,0,87,100))
local allf={ sf1,sf2}
--创建动画
local animation=cc.Animation:createWithSpriteFrames(allf,0.1)
local animate=cc.Animate:create(animation)
sp:runAction(cc.RepeatForever:create(animate))