2011-12-21 58 views
3

我读现有的一些成熟的游戏的源代码,我来到这个防空火炮:这个平台游戏的滚动代码究竟做了什么?

/* assign the horizontal position of the TileMap on the screen to offsetX 
    * this, center aligns the player. */ 
    int offsetX = width/2 - Math.round(player.getX()) - TILE_SIZE; 
    /* stop the map scrolling if the player reaches the two ends 
    * of the map */ 
    offsetX = Math.min(offsetX, 0); // if offsetX < 0 , offsetX = 0 
    offsetX = Math.min(offsetX, width-tileMap.getWidth()); //if offsetX > map width, offsetX = mapwidth 

    int offsetY = height - toPixels(tileMap.getHeight()); // not really necessary, I think 

    int firstTile = toTiles(-offsetX); // ??? 
    int lastTile = firstTile + toTiles(width) + 1; // why the +1 

我评论过一些地方我想我明白了,问别人的意见的问题。

打扰我大部分的事情是:

1- OFFSETX如何分配(width/2 ... ?)我已经认识到其指定OFFSETX一些地方,其中心对齐玩家在地图上,但我不知道如何

2 - 在第三行中,为什么开发人员编写width - tileMap.getWidth()

注意:如果一行一行地解释代码太麻烦,请给我一个粗略的想法,也许有图表?开发人员想要在这里做什么。谢谢。

+0

我不明白你的第一个问题 - 你说你懂'宽/ 2'(居中对齐的球员,你是对的,从我可以告诉),和这里没有代码说'player.x = offsetX',这就是我想'怎么样...' – Prescott 2011-12-21 04:56:02

+0

'player.x = offsetX'是在这段代码之后完成的,对不起,我没有发布它。我想问的是,公式'width/2 - Math.round(player.getX()) - TILE_SIZE;'如何在屏幕上返回水平位置,该屏幕与播放器居中对齐。我不明白_formula_背后的理论,但我明白它的作用。 – ApprenticeHacker 2011-12-21 05:02:42

回答

1

1-i认为这个偏移是用于绘制不是用于居中对齐的贴图,这个函数在玩家移动时用负数增加偏移量,他移动的距离越远,越高,则越高偏移是。

例如:

现在这个偏移用于绘制与负偏移瓦片,换言之,进一步离开,在这种情况下tileMap[0]=(10-160,10) 这意味着tilemap的[0]是在屏幕的范围(瓦向左滚动,播放器右侧)

2,我想这应该是offsetX = Math.max(offsetX, width-tileMap.getWidth()); 在这种情况下,其额外的检查,只滚动到地图的尽头。

例如:

width=300 
    player.getX()=900 
    TILE_SIZE=10 
    tileMap[last]=(1010,10) 
    tileMap.getWidth()=1000 

    offset=300/2-900-10 
    offset= -760 
    offsetX = Math.min(-760, 0); 
    offsetX = -760 
    offsetX = Math.max(-760, 300-1000); 
    offsetX = -700 
+0

+1,哇,谢谢! – ApprenticeHacker 2011-12-21 14:11:17