背景
- 背景图大小为 (480, 852)
- 将canvas的大小设置为(480,800),中心点的位置设置为(240, 400)
- 创建一个空节点bg,里面包含两张背景图, 空节点的位置为(240, 410)
- 一张位置为(0, 0)
- 一张位置为(0, 852)
- 两张背景图循环展示
- 在 Scripts文件夹下创建BgControl.ts,将这个脚本文件挂载在空节点bg上
update (dt) {
for (const bgNode of this.node.children) {
bgNode.y -= 50 * dt
if(bgNode.y < -852){
bgNode.y += 852 * 2
}
}
}
玩家
- 拖拽玩家的图片创建玩家节点player
- 在 Scripts文件夹下创建PlayerControl.ts,将这个脚本文件挂载在玩家节点player上
const { ccclass, property } = cc._decorator;
@ccclass
export default class PlayerControl extends cc.Component {
@property(cc.Prefab)
bulletPre: cc.Prefab = null
start() {
this.node.on(cc.Node.EventType.TOUCH_MOVE, (event) => {
this.node.setPosition(event.getLocation())
})
this.schedule(() => {
let bullet = cc.instantiate(this.bulletPre)
bullet.setParent(cc.director.getScene())
bullet.x = this.node.x
bullet.y = this.node.y + 60
}, 0.5)
cc.director.getCollisionManager().enabled = true
}
}
子弹
- 拖拽子弹图片创建子弹节点bullet
- 子弹碰到敌人,自己和敌人都销毁
- 子弹出了屏幕,自动销毁
- 在 Scripts文件夹下创建BulletControl.ts,将这个脚本文件挂载在子弹节点bullet上
import EnemyControl from "./EnemyControl";
const { ccclass, property } = cc._decorator;
@ccclass
export default class BulletControl extends cc.Component {
@property
speed: number = 800
start() {
}
update(dt) {
this.node.y += this.speed * dt
if (this.node.y > 820) {
this.node.destroy()
}
}
onCollisionEnter(other) {
console.debug("peng")
if (other.tag == 1) {
other.getComponent(EnemyControl).die()
this.node.destroy()
}
}
}
敌人
- 拖拽敌人图片创建敌人节点enemy
- 敌人被子弹碰撞,销毁
- 敌人碰撞tag为1
- 在 Scripts文件夹下创建EnemyControl.ts,将这个脚本文件挂载在敌人节点enemy上
const { ccclass, property } = cc._decorator;
@ccclass
export default class EnemyControl extends cc.Component {
isDie: boolean = false
start() {
}
update(dt) {
if (!this.isDie) {
this.node.y -= 300 * dt
}
if (this.node.y < -850) {
this.node.destroy()
}
}
die() {
this.isDie = true
cc.loader.loadRes("enemy0_die", cc.SpriteFrame, (err, res) => {
this.node.getComponent(cc.Sprite).spriteFrame = res
})
setTimeout(() => {
this.node.destroy()
}, 300);
}
}
敌人管理
- 创建一个空节点为EnemyManager
- 将enemy作为预设体
- 在 Scripts文件夹下创建EnemyManager.ts,将这个脚本文件挂载在EnemyManager上
const { ccclass, property } = cc._decorator;
@ccclass
export default class EnemyManager extends cc.Component {
@property(cc.Prefab)
enemyPre: cc.Prefab = null;
start() {
this.schedule(() => {
console.debug(222)
let enemy = cc.instantiate(this.enemyPre)
enemy.setParent(cc.director.getScene())
enemy.y = this.node.y
enemy.x = Math.random() * 400 + 20
}, 2)
}
}