1.预览
2.思路分析
-
生成小恐龙并添加点击事件跳起动画
-
随机生成仙人掌并添加从右到左平移动画
-
获取恐龙和仙人掌的位置进行判断,是否重叠。
-
初始化分数,进行递增,持续到游戏结束。
3.代码分析
初始化恐龙和仙人掌的动画
data () {
return {
speed: 400, //恐龙跳跃速度以及仙人掌移动速度
dinosaurAnimationData: {},
treeAnimationData: {}
}
}
mounted () {
this.dinosaurAnimation = uni.createAnimation()
this.treeAnimation = uni.createAnimation()
}
恐龙永远是在左下方,只需要上下移动。而仙人掌需要从右到左移动
<!-- 点击跳起按钮恐龙跳动 -->
jump () {
this.dinosaurAnimation.translateY(-200).step({duration:this.speed})
this.dinosaurAnimationData = this.dinosaurAnimation.export();
setTimeout(() => {
this.dinosaurAnimation.translateY(0).step({duration:this.speed})
this.dinosaurAnimationData = this.dinosaurAnimation.export()
}, 300)
}
<!-- 仙人掌移动完成后复位 -->
this.treeAnimation.translateX(-windowWidth-370).step({duration: this.speed}).translateX(0).step({duration:0})
在仙人掌移动到恐龙位置的时候进行判断恐龙是否跳起
<!-- 获取恐龙位置 -->
uni.createSelectorQuery().in(this).select('.dinosaur').boundingClientRect(result => {
if (result) {
peoplePos = [result.left, result.bottom, result.width]
}
}).exec();
<!-- 获取仙人掌位置 -->
uni.createSelectorQuery().in(this).selectAll('.tree-list').boundingClientRect(result => {
if (result) {
result.forEach(item => {
//判断仙人掌是否移动到恐龙的位置
if (item.left + 50 <= peoplePos[0] + peoplePos[2] && item.left >= peoplePos[0]) {
//判断恐龙和仙人掌是否重合 重合=结束 不重合=恐龙跳起了
if ((item.bottom - item.height) > peoplePos[1]) {
} else {
this.returnFlag = true
this.treeAnimationData = {}
this.dinosaurAnimationData = {}
}
}
})
}
}).exec();
效果
遇到的问题
-
原本打算用canvas做动画效果,后来发现uni-app中canvas里面的requestAnimationFrame不生效,后来用了animation。
-
animation中step()连续调用会出现动画不匹配,但在开发者工具中调试器里面没有问题,这个问题是animation在手机端存在的bug,至今都未修复。
结语
大体思路也就这样,还剩细节方面需要调整一下,就可以了~