Reputation: 33
So I've been making a small game (by small, I mean a red box moving around a screen) and I decided, for some reason, to add a feature that automatically sets a certain aspect ratio so it can work on all window shapes and sizes. Now, my keyframe animations are broken because the use pixel coordinates. Here is the CSS with just the left animation:
#stage{
border: 1px solid black;
margin: auto;
}
#player{
background-color: red;
position: relative;
}
@keyframes moveLeft{
0%{transform: translateX(0px);}
80%{transform: translateX(-60px);}
}
.animateLeft{animation: moveLeft 125ms ease-out;}
And the JavaScript (removed non-left movements):
var game = {};
game.fps = 50;
var player = document.getElementById('player');
var stage = document.getElementById('stage');
var playerX = 0, playerY = 0;
var stageWidth, stageHeight;
var borderAspectRatio = 16/9;
var a = 0;
var isPlayerMoving = 0, newPlayerX = 0, newPlayerY = 0;
function checkPlayerMovement(){
if(player.classList == 'animateLeft'){
isPlayerMoving = 1;
}
else{
isPlayerMoving = 0;
}
};
function playerHalt(){
isPlayerMoving = 0;
setNewPlayerPosition();
player.classList.remove('animateLeft');
};
function playerLeft(){
player.classList.add('animateLeft');
setTimeout(playerHalt,100);
};
function setNewPlayerPosition(){
if(isPlayerMoving == 0){
playerX = newPlayerX;
playerY = newPlayerY;
}
setPlayerPosition();
};
function setPlayerPosition(){
var playerSideLength = stageHeight/15;
player.style.width = `${playerSideLength}px`
player.style.height = `${playerSideLength}px`
player.style.left = `${playerX + (stageWidth - playerSideLength) / 2}px`;
player.style.bottom = `${playerY - (stageHeight - playerSideLength) / 2}px`;
};
document.addEventListener('keydown', function(event) {
if(event.keyCode == 65) {a=1;}
});
document.addEventListener('keyup', function(event) {
if(event.keyCode == 65) {a=0;}
});
function playerMotion(){
checkPlayerMovement();
if(a == 1){
if(isPlayerMoving == 1){
return;
}
else{
newPlayerX -= 60;
playerLeft();
}
}
};
function scale(){
var w = window.innerWidth;
var h = window.innerHeight;
if(w/h > borderAspectRatio){
stageWidth = 0.96*h*borderAspectRatio;
stageHeight = 0.96*h;
}
else{
stageWidth = 0.96*w;
stageHeight = 0.96*w/borderAspectRatio;
}
stage.style.width = `${stageWidth}px`;
stage.style.height = `${stageHeight}px`;
};
game.run = function() {
scale();
setPlayerPosition();
playerMotion();
};
game._intervalId = setInterval(game.run, 1000 / game.fps);
How can I change it to use some percentage (or something idk) of the screen instead of pixels?
Upvotes: 2
Views: 625
Reputation: 46
Check out the Realtive length units on MDN (here)
especially the part about vh and vw, they're 1% of the viewport's height and 1% of the viewport's width respectively.
Upvotes: 1