简体   繁体   中英

Properly centering div based on child element

This is a repost from StackExchange's GameDev section, yet, I find that the problem seems more applicable to StackOverflow because it pertains more to CSS, JS, and positioning techniques rather than JavaScript topics (mostly UnityScript and Phaser) discussed on the former.

I've been making a roguelike-style game in HTML5 without using canvas (only divs) with pure JS ( fiddle! ). I've been trying to enlarge the tile size (font size) while keeping the player centered within the camera. For some reason, when the tile size isn't equal to the map size, the camera will be slightly off.

Note that the 3D effect is on purpose; I believe it adds some much needed depth, and just looks super cool. :D

When tileScale (line 4 in the fiddle) is 9 (very undesirable; the dots on the player's y axis should be aligned, not at a slight angle):

相机关闭!

When tileScale is 25 (on point!):

相机对准点。

Here's some relevant (trimmed) code:

window.onresize = function(){
    game.viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    game.viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    game.windowSize = Math.min(game.viewportWidth, game.viewportHeight);
    // Droid Sans Mono has a ratio of 3:4 (width:height), conveniently.
    // This may be problematic. I'm not sure.
    game.tileWidth = game.windowSize*.6 / game.tileScale;
    game.tileHeight = game.windowSize*.8 / game.tileScale;
}

// Update the camera position (needs help?)
this.updateCamera = function(){
    // Get player coordinates (-.5 because we need to get the player tile center)
    // times the tileWidth plus the game window (inner square) size divided by two.
    var left = ((-game.player.x-.5)*game.tileWidth+game.windowSize/2)+"px";
    var top = ((-game.player.y-.5)*game.tileHeight+game.windowSize/2)+"px";
    game.planeContainer.style.left = left;
    game.planeContainer.style.top = top;
}

How can I ensure that the dots in the center of the screen will be always lined up, instead of on a slight angle? My current evidence suggests that the position of the game.planeContainer object isn't being established correctly.

I know this is a super-tough problem, so any help will be greatly appreciated. Thanks in advance!

( Another fiddle link, in case you skimmed over the first one. :D )

Remove this line from your css stylings on .inner-text to take out the skew:
transform: translate(-50%, -50%);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM