FEE_MathRunner/js/allg.js
2024-09-04 22:10:36 +02:00

106 lines
2.4 KiB
JavaScript

// animation
let playerAnim = [];
let tomAnim = [];
let enemyAnim = [];
//player
let playerAnimState = 0;
let runDirection = 0;
let runSpeed = 18;
let animationSpeed = 50;
let currentPosition = 0;
let player = document.querySelector("#fuchs");
let playerSprite = document.querySelector("#fuchs img");
let dIsPressed = false;
let aIsPressed = false;
let runAnimation;
// Map
const boxBorderLeft = -40;
const boxBorderRight = 840;
fillArrays();
startAnimation();
//currentPosition = window.getComputedStyle(player).left;
// Pictures
function fillArrays()
{
fillArray("fuchs_", 8, playerAnim);
fillArray("tom_", 3, tomAnim);
fillArray("enemy_",3, enemyAnim);
}
// startGame
let start = setInterval(gameLoop, 50);
function gameLoop()
{
move();
}
//-------------------------------------------------------------- Animation -----------------------------------------------------------------------
function startAnimation()
{
runAnimation = setInterval(playerRunAnim, animationSpeed);
}
function playerRunAnim()
{
if(playerAnimState == 8)
{
playerAnimState = 0;
}
playerSprite.src = playerAnim[playerAnimState];
playerAnimState++;
}
//------------------------------------------------------------- checkInput ------------------------------------------------------------------
document.addEventListener('keydown', function(event) {
if(event.key == "d")
{
if(runDirection != 1)
{
playerSprite.style.transform = 'scaleX(1)';
}
runDirection = 1;
dIsPressed = true;
}
else if(event.key == "a")
{
if(runDirection != -1)
{
playerSprite.style.transform = 'scaleX(-1)';
}
runDirection = -1;
aIsPressed = true;
}
});
document.addEventListener('keyup', function(event)
{
if(event.key == "d")
{
dIsPressed = false;
}
else if(event.key == "a")
{
aIsPressed = false;
}
if(!aIsPressed && !dIsPressed)
{
runDirection = 0;
}
});
//---------------------------------------------------------- Move Player ------------------------------------------------------------
function move()
{
let nextPosition = currentPosition + runDirection * runSpeed;
if(nextPosition > boxBorderLeft && nextPosition < boxBorderRight)
{
currentPosition = nextPosition;
}
player.style.left = currentPosition + "px";
}