版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/winnershili/article/details/86545275
前言 不搭后语
好久没写博客了, 年底都很忙的, 希望在这个IT寒冬之年, 大家不要忘记继续自己的理想
昨天测试了一个瓦片地图的小东西 今天主要的目的是记录! 例子使用TypeScript写的
我很喜欢这语言 写代码很舒适 尤其是我这种从C#和JAVA过来的同学 感觉真棒 比Dart 还有 科特林 舒服
一 首先加载一个地图
showMap(){
//创建TiledMap实例
this.tMap = new Laya.TiledMap();
//创建Rectangle实例,视口区域
let viewRect:Laya.Rectangle = new Laya.Rectangle(0,0,Laya.stage.width,Laya.stage.height);
//创建TiledMap地图
this.tMap.createMap("comp/map/test_map.json",viewRect,Laya.Handler.create(this, this.onLoadMap));
}
二 加载完毕了就把主人公放进去
这里的pass是瓦片地图的第一层 由于目前设计的地图就没什么可说的了
onLoadMap(){
this.pass = this.tMap.getLayerByIndex(0);
this.initHero();
}
把主人公放到地图上
initHero(){
this.hero = new Hero();
Laya.stage.addChild(this.hero);
Laya.timer.frameLoop(1,this,this.animate);
Laya.stage.on(Laya.Event.MOUSE_UP,this,this.heroMove);
}
主人公默认是不停移动的
heroMove(){
this.targetX = Laya.stage.mouseX;
this.targetY = Laya.stage.mouseY;
}
三 找到主人公所在位置的2-4个格子
因为人物比格子小, 所以只有2-4个格子 如果比格子大 按大几倍来计算
其中的数字70是格子的大小 30个是主人公的大小, 设计的比较粗糙 见谅
getMapPos(x:number,y:number,v:number){
let pos = [];
let mapX = Math.floor(x/70);
let mapY = Math.floor(y/70);
pos.push({x:mapX,y:mapY})
if(x%70+30>70){
pos.push({x:mapX+1,y:mapY})
}
if(y%70+30>70){
pos.push({x:mapX,y:mapY+1})
}
if(x%70+30>70&&y%70+30>70){
pos.push({x:mapX+1,y:mapY+1})
}
return pos;
}
四 最后计算出主人公所在方向的格子 是否被阻挡 被没有用到自动寻路 有点简单
animate(){
//计算差距
let dx:number = this.targetX - this.hero.x;
let dy:number = this.targetY - this.hero.y;
if(Math.abs(dx)<5&&Math.abs(dy)<5){
return;
}
//计算出角度
let angle:number = Math.atan2(dy,dx); //弧度制
//console.info(angle);
//根据弧度 计算出目标点坐标
let nextX = this.hero.x + Math.cos(angle)*this.hero.speed;
let nextY = this.hero.y + Math.sin(angle)*this.hero.speed;
//获取2-4个点
let poses = this.getMapPos(nextX,nextY,30);
for(let pos of poses){
let id = this.pass.getTileData(pos.x,pos.y);
let a = this.tMap.getTileProperties(0,id-1,"block");
if(a){
return;
}
}
this.hero.x = nextX;
this.hero.y = nextY;
}
重要的方法有 getTitleData 和getTileProperties
这里有个自定义的属性block 来决定是否可以通过
很多地方可以用常量来控制,
就是一个测试就不那么严谨啦!
记录完毕