Video showing the problem. Im making JavaScript project about horse race game, and on race track there are obstacles that character should detect and trigger the animation of jumping. For no obvious reason, the animation is triggering in bad way and the character fly out of the screen, after a while it's returning and same thing occurs at second obstacle. In the beggining of the video im just showing how the animation should look like.
The logic is build about setInterval and function with element.offsetTop. Start button triggers the interval which triggers function of moving. Inside that function, the position of the character and currently selected (by i counter) obstacle are checked. When the character gets 80 pixels before obstacle, if-statement triggers the animation by adding class name to element, and after that I have no idea what is happening. Instead of imitating Daedalus it should perform the animation smoothly, trigger another if-statement to count the bush and remove the given class name to make another jump viable.
The CSS code of animation
.horse.jump {
animation-iteration-count: 500;
transform: rotate(0deg) scale(1,1);
margin-top: 0;
animation-direction: initial, initial;
background-position:48px -192px;
animation-fill-mode: backwards;
animation: jump 1s;
}
The JS code
var horse = document.getElementsByClassName('horse');
var bush = document.getElementsByClassName('bush');
var i = 0; //Counter for the next obstacle
function horseMoving () {
//Function connecting Start Button with
// moving function by interval
setInterval(moveDown, 9);
}
function moveDown (){
// Cheking character position
var positionHorseUp = horse[0].offsetTop;
//Checking for the current closest obstacle
var positionBushUp = bush[i].offsetTop;
horse[0].classList.add('runDown');
horse[0].style.top = positionHorseUp + 1 + 'px';
//When the character gets close to obstacle
if (positionHorseUp==positionBushUp-80) {
//Makes horse to jump
horse[0].classList.add('jump');
}
//When the character gets away from obstacle
if (positionHorseUp==positionBushUp+20) {
//Takes away the jump class
horse[0].classList.remove('jump');
// This statements prevents an array
// from getting out of elements
// and triggers cheking for next obstacle
if (i<5) {
i++; }
}
}
// These 2 functions are only for video purpose
function showJump() {
horse[0].classList.add('jump')}
function showJump2() {
horse[0].classList.remove('jump')}
function loadFunction() {
var startButton = document.getElementById('start')
startButton.addEventListener('click', horseMoving)
// These 2 lines are only for video purpose
startButton.addEventListener('click', showJump2)
horse[0].addEventListener('click', showJump)
}
document.addEventListener('DOMContentLoaded', loadFunction);
Aucun commentaire:
Enregistrer un commentaire