2011-12-21 20 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