cocos2dx for xna 基于地图的碰撞检测和信息提示

在上一篇里基本上已经实现了人物的行走,但是,人物的行走需要一定的规划,而不是漫游在地图之上。

这个规划就是碰撞检测。

上一篇里,我们用了titled这个编辑器来编辑地图。这个编辑器把地图分了不同的层,所以我们可以根据不同的层的名字来做为碰撞检测的条件。

/// <summary>
        /// 根据目的位置判断是否碰撞类型
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public int checkCollision(CCPoint p)
        {
            //tmxMap.MapSize.width和tmxMap.MapSize.height是定义在tmx地图上的坐标,而不是UI界面上的坐标
            //即是(2,3)=(120,180)
            if (p.x < 0 || p.x > tmxMap.MapSize.width || p.x < 0 || p.y > tmxMap.MapSize.height)
                return (int)Dtype.KWall;
            int titleGid = tmxMap.layerNamed("floor").tileGIDAt(p);
            if (titleGid != 0)
                return (int)Dtype.TNone;
            return (int)Dtype.KWall;
        }

代码如上,由于检测的是floor层,所以tmxMap.layerNamed("floor").tileGIDAt(p);返回的值只有两种情况。当检测到非零,则表明在floor层这里有“地图块”,说明可以行走,反之亦反。

接下来,介绍cocos2d-x for xna 的信息提示:

首先,显示信息也是一个“精灵”。所以我们可以理解为,我们把显示信息这个动作(CCAction)交给一个“精灵”(CCLabelTTF)去执行。

所以,代码的构建如下:

1.显示信息的位置:CCPoint

2.信息精灵:CCLabelTTF

3.动作:CCAction

CCPoint tagPoint=new CCPoint(startPosition.x+0,startPosition.y+60);
            CCLabelTTF tipLabel = CCLabelTTF.labelWithString(tip, "Arial", 10);
            tipLabel.position = tagPoint;
            addChild(tipLabel, 2, 1);
            CCAction action = CCSequence.actions(
                CCMoveBy.actionWithDuration(0.5f, new CCPoint(0, 60)),
                CCDelayTime.actionWithDuration(0.5f),
                CCFadeOut.actionWithDuration(0.2f),
                 CCCallFuncN.actionWithTarget(this, onShowTipDone)
                );
            tipLabel.runAction(action);
原文地址:https://www.cnblogs.com/dieaz5/p/2955201.html