tiledmap
通过图层来放不同的叠加场地
对象层可以保存信息并且可以通过代码获取
对象层在可覆盖层之上,在遮盖层之下
MapControl
const {ccclass, property} = cc._decorator;
@ccclass
export default class MapContrrol extends cc.Component {
map:cc.TiledMap;
player:cc.Node = null;
start () {
//获取地图信息
this.map = this.getComponent(cc.TiledMap);
//普通层
//this.map.getLayer();
//对象层
let playerLayer = this.map.getObjectGroup("player");
//提取某个对象
let playerObj = playerLayer.getObject("startpos");
//判断是否为玩家对象
if(playerObj.isPlayer == true){
//加载玩家预设体
cc.loader.loadRes('player',cc.Prefab,(res,playerPre)=>{
//创建玩家
this.player = cc.instantiate(playerPre);
this.player.setParent(this.node.children[2].children[0]);
this.player.x = playerObj.x;
this.player.y = playerObj.y;
});
}
}
update(dt){
//摄像头跟随玩家
if(this.player !== null){
cc.Camera.main.node.x = this.player.x - 240;//减去半个屏幕的位置使其置于左下角
cc.Camera.main.node.y = this.player.y - 160;
}
}
}
Input
const {ccclass, property} = cc._decorator;
@ccclass
export default class Input {
private static instance : Input = null;
//水平轴
horizontal:number = 0;
//垂直轴
vertical:number = 0;
static get Instance(){
if(this.instance == null){
this.instance = new Input();
}
return this.instance;
}
constructor(){
//键盘按下
cc.systemEvent.on(cc.systemEvent.EventType.KEY_DOWN,(event)=>{
if(event.keyCode == cc.macro.KEY.w){
this.vertical = 1;
}else if(event.keyCode == cc.macro.KEY.s){
this.vertical = -1;
}
if(event.keyCode == cc.macro.KEY.a){
this.horizontal = -1;
}else if(event.keyCode == cc.macro.KEY.d){
this.horizontal = 1;
}
});
//键盘抬起
cc.systemEvent.on(cc.systemEvent.EventType.KEY_UP,(event)=>{
if(event.keyCode == cc.macro.KEY.w&&this.vertical == 1 ){
this.vertical = 0;
}else if(event.keyCode == cc.macro.KEY.s&&this.vertical == -1){
this.vertical = 0;
}
if(event.keyCode == cc.macro.KEY.a&&this.horizontal == -1){
this.horizontal = 0;
}else if(event.keyCode == cc.macro.KEY.d&&this.horizontal == 1){
this.horizontal = 0;
}
});
}
}
PlayerControl
import Input from "./Input";
const {ccclass, property} = cc._decorator;
@ccclass
export default class PlayerControl extends cc.Component {
//速度
speed: number =20;
start () {
}
update (dt) {
//移动dt帧间隔
this.node.x += this.speed *dt*Input.Instance.horizontal;
this.node.y += this.speed*dt*Input.Instance.vertical;
}
}