FEE_MathRunner/js/allg.js
2024-08-29 08:18:22 +02:00

97 lines
2.2 KiB
JavaScript

let playerAnim = [];
let tomAnim = [];
let enemyAnim = [];
let playerAnimState = 0;
let runDirection = 0;
let runSpeed = 12;
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;
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()
{
currentPosition = currentPosition + runDirection * runSpeed;
player.style.left = currentPosition + "px";
}