LayaAir引擎——(六)


LayaAir引擎——TiledMap地圖圖塊屬性獲取和進行牆壁碰撞檢測

 

需要的軟件:

TiledMap

LayaAir IDE 1.0.2版本

 

所畫的地圖:

pass層:

floor層:

 

pass層格子屬性:

白色格子: id:48,自定義屬性 isCanPass:true

黑色格子:id:44,自定義屬性 isCanPass:false

floor層格子屬性

五芒星格子:id:0

石頭格子:id:27

礦車格子:id:22

 

1.前提代碼

Laya.init(576, 576);
	
var player;
var obj;
var floor;
var pass;

var map1 = new TiledMap();
map1.createMap("map/map1/town1.json",new Rectangle(0,0,576, 576),Handler.create(this,onMapLoaded));

function onMapLoaded(){
     pass = map1.getLayerByIndex(0);//獲取通行層
 
     player = new Sprite();
     player.loadImage("map/map1/player.png",0,0,48,48);
     Laya.stage.addChild(player);

     Laya.stage.on(laya.events.Event.KEY_DOWN,this,onKeyDown);//設置鍵盤監聽事件
}

2.重點代碼

function onKeyDown(e) {
  switch (e.keyCode) {
    case 38:{
      if ( (player.y - 48) <= 0) {
        player.y = 0;
      }else{
             var a = pass.getTileData(player.x / 48, (player.y - 48)/ 48);
             var b = map1.getTileProperties(0, a-1, "isCanPass");
             if(b){
          player.y -= 48;
        }
          }
      break;
      }
      case 40:{
          if ( (player.y + 48) >= (576- 48)){
        player.y = 576 - 48;
          }else{
             var a = pass.getTileData(player.x / 48, (player.y + 48)/ 48);
             var b = map1.getTileProperties(0, a-1, "isCanPass");
             if(b){
          player.y += 48;
        }
          }
          break;
      }   
      case 37:{
      if ( (player.x - 48) <= 0) {
        player.x = 0;
      }else{
        var a = pass.getTileData( (player.x - 48)/ 48,player.y/ 48);
        var b = map1.getTileProperties(0, a-1, "isCanPass");
        if(b){
           player.x -= 48;
        }
      }
      break;
      }
      case 39:{
      if ( (player.x + 48) >= (576 - 48)) {
        player.x = 576 - 48;       }else{         var a = pass.getTileData( (player.x + 48)/ 48,player.y/ 48);         var b = map1.getTileProperties(0, a-1, "isCanPass");         if(b){           player.x += 48;         }       }
    break;
    }  
  } }

 

3.其中代碼重點

MapLayer.getTileData(x,y)

參數:

x:格子在地圖上的x坐標,等同於屏幕坐標/格子的寬度

y:格子在地圖上的y坐標,等同於屏幕坐標/格子的高度

返回:格子在紋理圖塊上的id值+1

 

例子:

 var a = pass.getTileData( 0, 0);
 console.log(a);//49(白色格子ID:48)

 

TiledMap.getTileProperties(textureIndex,tileIndex,propertyName);

參數:

textureIndex:格子所在的紋理圖塊的索引

tileIndex:格子在紋理圖塊上的索引

propertyName:自定義屬性的名稱

返回:屬性內容

 

例子:

var b = map1.getTileProperties(0, 44, "isCanPass");
console.log(b);//false(黑色格子)

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM