1. Preview

2. Analysis of ideas

  • Generate a small dinosaur and add a click event jump animation

  • Randomly generate cactus and add pan animation from right to left

  • Get the dinosaur and the cactus and determine if they overlap.

  • Initialize the score and increment it until the end of the game.

3. Code analysis

Initialize dinosaur and cactus animations

DinosaurAnimationData () {return {speed: 300, // dinosaurAnimationData: {}, treeAnimationData: {} } } mounted () { this.dinosaurAnimation = uni.createAnimation() this.treeAnimation = uni.createAnimation() }Copy the code

Dinosaurs are always down to the left, they just move up and down. Cactus needs to move from right to left

<! -- click jump button dinosaur jump - > 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) } <! - after the completion of the cactus mobile reset -- > this. TreeAnimation. TranslateX (windowWidth - 370). Step ({duration: this.speed}).translateX(0).step({duration:0})Copy the code

Determine if the dinosaur jumped when the cactus moved into its position

<! Select ('.dinosaur').boundingClientRect(result => {if (result) {uni. CreateSelectorQuery ().in(this).select('.dinosaur').boundingClientRect(result => {if (result) { peoplePos = [result.left, result.bottom, result.width] } }).exec(); <! In (this).selectAll('.tree-list').boundingClientRect(result => {if (result) { 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();Copy the code

The effect

Problems encountered

  • I originally intended to use canvas for animation, but later I found that the requestAnimationFrame in canvas in UNI-App did not work, so I used animation.

  • In animation, step() is continuously called, there will be animation mismatch, but there is no problem in the debugger of developer tools. This problem is a bug in animation on the mobile side, which has not been fixed up to now.

conclusion

General idea is also such, still need to adjust the details, it is ok ~Copy the code