根据子元素正确居中div

时间:2015-03-17 03:07:11

标签: javascript html css html5 roguelike

这是来自StackExchange的GameDev部分的转贴,然而,我发现这个问题似乎更适用于StackOverflow,因为它更多地涉及CSS,JS和定位技术,而不是讨论JavaScript主题(主要是UnityScript和Phaser)在前者。

我一直在HTML5 中制作一个 roguelike风格的游戏,而不使用纯JS (仅限div) fiddle! )。我一直在尝试放大磁贴大小(字体大小),同时保持播放器在摄像机中居中。由于某种原因,当磁贴大小不等于地图大小时,摄像机将稍微离开。

请注意,3D效果是有目的的;我相信它增加了一些非常需要的深度,而且看起来非常酷。 :d

tileScale(小提琴中的第4行)为9时(非常不受欢迎;玩家y轴上的点应该对齐,而不是略微倾斜):

The camera is off!

tileScale25时(点上!):

The camera is on point.

这是一些相关的(修剪过的)代码:

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;
}

如何确保屏幕中心的点总是排成一行,而不是略微倾斜?我目前的证据表明game.planeContainer的位置对象未正确建立。

我知道这是一个非常棘手的问题,所以任何帮助都将不胜感激。提前谢谢!

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

1 个答案:

答案 0 :(得分:2)

从.inner-text上的css样式中删除此行以取出偏斜:
transform:translate(-50%, - 50%);