【发布时间】:2018-07-13 17:08:07
【问题描述】:
Video showing the problem. 我正在制作关于赛马游戏的 JavaScript 项目,并且在赛道上存在角色应该检测并触发跳跃动画的障碍。没有明显的原因,动画触发不好,角色飞出屏幕,过了一会儿它又回来了,同样的事情发生在第二个障碍物上。在视频的开头,我只是展示了动画应该是什么样子。
逻辑是关于 setInterval 和 element.offsetTop 的功能。 开始按钮触发触发移动功能的间隔。在该函数中,检查角色的位置和当前选择的(通过 i 计数器)障碍物。当角色在障碍物之前获得 80 像素时,if 语句通过向元素添加类名来触发动画,之后我不知道发生了什么。它不应该模仿代达罗斯,而是应该流畅地执行动画,触发另一个 if 语句来计算灌木丛并删除给定的类名以使另一个跳跃可行。
动画的CSS代码
.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;
}
JS 代码
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);
【问题讨论】:
-
还是解决不了这个问题,我试过跟踪if语句触发了多少次,但什么都没解决
标签: javascript if-statement animation