---
title: "【cocos2d-html5】 如何使用cocos2d-html5 制作基于tile地图的游戏教程：第一部分"
author: "nhy520"
date: "2013-09-27T23:55:52Z"
tags: []
categories: ["移动开发"]
slug: "cocos2d-html5-cocos2d-html5-tile"
draft: false
lastmod: "2013-09-27T23:55:52Z"
id: 1948460
url: "https://nhy520.iteye.com/blog/1948460"
---

好久没有写博客了，自从自己用了云笔记后，喜欢在云笔记里记录，但最近发现自己cocos2d-html5的文章还是比较少，所以把最近通过别人的笔记cocos2d的关于tiled地图使用的文章转成了ch5终于跑起来了。

参考原文：  
http://www.raywenderlich.com/1163/how-to-make-a-tile-based-game-with-cocos2d

中文参考稿：  
http://www.cnblogs.com/andyque/archive/2011/04/11/2012852.html

关于如何创建 tiled地图文件tmx 文件的内容，请参考以上的中文参考稿，已经写的比较清楚了。唯一不清楚的就是tmx文件里面要修改你的图片相对路径：  
如：  
 &lt;tileset firstgid="1" name="tmw\_desert\_spacing" tilewidth="32" tileheight="32" spacing="1" margin="1"&gt;  
  &lt;image source="tmw\_desert\_spacing.png" trans="ff00ff" width="265" height="199"/&gt;  
 &lt;/tileset&gt;

 

本文采用的cocos2d-html5版本为v2.1.5

现把我的翻译脚本copy上来供大家参考：

 

var MyLayer = cc.Layer.extend({  
    isMouseDown: false,  
    helloImg: null,  
    helloLabel: null,  
    circle: null,  
    sprite: null,  
    size: null,  
    \_tileMap: null,  
    player: null,  
    init: function () {  
        this.\_super();  
        // ask director the window size  
        this.size = cc.Director.getInstance().getWinSize();  
        // 加载tmx  
        var tileMap = cc.TMXTiledMap.create(tmx\_001);  
        this.\_tileMap = tileMap;  
        this.addChild(this.\_tileMap, 1, 0);  
        // 获得对象层  
        var objectLayer = tileMap.getObjectGroup("Objects");  
        var array = objectLayer.getObjects();  
        var spawnPoint = array\[0];  
        var objX = spawnPoint\["x"];  
        var objY = spawnPoint\["y"];  
        var width = spawnPoint\["width"];  
        var height = spawnPoint\["height"];

        this.player = cc.Sprite.create(s\_Player);  
        this.player.setPosition(cc.p(objX, objY));  
        this.addChild(this.player, 1, 0);  
        this.setViewpointCenter(this.player.getPosition());

        // 添加事件监听  
        this.setTouchEnabled(true);  
    },  
    registerWithTouchDispatcher: function () {  
        // CCDirector::sharedDirector()-&gt;getTouchDispatcher()-&gt;addTargetedDelegate(this, 0, true);  
        cc.Director.getInstance().getTouchDispatcher().addTargetedDelegate(this, 0, true);  
    },  
    onTouchEnded: function (touch, event) {  
        var touchLocation = touch.getLocation();  
        touchLocation = this.convertToNodeSpace(touchLocation);

        //获得精灵当前位置  
        var playerPos = this.player.getPosition();  
        console.log("touchLocation.x: " + touchLocation.x);  
        console.log("touchLocation.y: " + touchLocation.y);  
        console.log("playerPos.x :" + playerPos.x);  
        console.log("playerPos.y :" + playerPos.y);

        /*  
         计算出touch点和精灵的位置之差。我们必须基于touch位置选择一个方向，因此，  
         首先，我们需要计算出是上下移动还是左右移动。然后，我们比较正负值，决定具体的方向。  
         \*/  
        var diff = cc.pSub(touchLocation, playerPos);  
        if (Math.abs(diff.x) &gt; Math.abs(diff.y)) {  
            if (diff.x &gt; 0) {  
                playerPos.x += this.\_tileMap.getTileSize().width;  
            } else {  
                playerPos.x -= this.\_tileMap.getTileSize().width;  
            }  
        } else {  
            if (diff.y &gt; 0) {  
                playerPos.y += this.\_tileMap.getTileSize().height;  
            } else {  
                playerPos.y -= this.\_tileMap.getTileSize().height;

            }

        }

        if (playerPos.x &lt;= (this.\_tileMap.getMapSize().width * this.\_tileMap.getTileSize().width) &&  
            playerPos.y &lt;= (this.\_tileMap.getMapSize().height * this.\_tileMap.getTileSize().height) &&  
            playerPos.y &gt;= 0 && playerPos.x &gt;= 0) {

            // 设置精灵位置  
            this.setPlayerPosition(playerPos);  
        }  
        this.setViewpointCenter(this.player.getPosition());  
    },  
    onTouchBegan: function (touches, event) {  
        // 返回true表明接受这个触摸  
        return true;  
    },  
    /\**  
     * 设置玩家所在的视窗  
     * @param position  
     * @returns {\*}  
     \*/  
    setViewpointCenter: function (position) {  
        // 屏幕大小  
        var winSize = this.size;  
        var x = Math.max(position.x, winSize.width / 2);  
        var y = Math.max(position.y, winSize.height / 2);  
        x = Math.min(x, (this.\_tileMap.getMapSize().width * this.\_tileMap.getTileSize().width) - winSize.width / 2);  
        y = Math.min(y, (this.\_tileMap.getMapSize().height * this.\_tileMap.getTileSize().height) - winSize.height / 2);  
        //console.log("x2 is : " + x + "    y2 is : " + y);  
        // 实际位置  
        var actualPosition = cc.p(x, y);

        // 坐标中心  
        var centerOfView = cc.p(winSize.width / 2, winSize.height / 2);

        //console.log("centerOfView x" + centerOfView.x + "y " + centerOfView.y);  
        // 计算两点间的差分。  
        var viewPoint = cc.pSub(centerOfView, actualPosition);  
        console.log("视窗 x ：" + viewPoint.x + " 视窗 y ：" + viewPoint.y);  
        // 设置当前层的视窗  
        this.setPosition(viewPoint);  
    },  
    setPlayerPosition: function (viewPoint) {  
        console.log("精灵位置 x " + viewPoint.x);  
        console.log("精灵位置 y " + viewPoint.y);  
        this.player.setPosition(viewPoint);  
    }  
});

var MyScene = cc.Scene.extend({  
    onEnter: function () {  
        this.\_super();  
        var layer = new MyLayer();  
        this.addChild(layer);  
        layer.init();  
    }  
});

 

如果有了这个文章，你还不能跑起来，那我只能发源码给你了，把邮箱发过来。

 

附件为源码和源码目录结构。