通过上两节课,我们已经创建好了项目,有了地图和主角,并且已经实现了主角向前跑动,但是跑着跑着主角就跑出地图了,这样还怎么玩游戏。所以,接下来我们需要实现地图随着主角滚动。
首先要在Player中添加一个函数setViewPointByPlayer。
Player.h代码(红框内是新加的)

Player.cpp:(新加的代码)



setViewPointByPlayer()函数的功能是判断当主角的坐标改变时,是否需要滚动地图。
另外,Player要重写父类的setTagPosition函数,如上代码所显示,在原父类的实现上,再加上setViewPointByPlayer()函数。
setTiledMap函数里的操作大家可以先忽略,这涉及到retain和release, 将在后面的章节中讲解。总之就是保留map的引用。
最后,打开TollgateScene.cpp的addPlayer函数,在创建Player对象之后,再调用Player的setTiledMap函数,如下代码:

现在运行项目,就可以看到地图随着主角滚动了。
效果图:
