• 果实上浮 (减小 y 轴坐标,让果实上浮)

    我们需要思考一下逻辑。

    随着时间变化,我们之前在 game-loop 文件里面有一个 deltaTime ,通过它我们来实现随时间变化。

    修改你的 fruits.ts 文件

    1. import { deltaTime } from "./game-loop";
    2. class Fruits{
    3. num: number = 30; // 绘画果实的数量
    4. alive: boolean[] =[]; // 判断果实是否存活
    5. x : number[]= []; // 果实的 x 坐标数组
    6. y : number[] = []; // 果实的 y 坐标数组
    7. diameter : number[] = []; // 果实的直径数组
    8. speed: number[] = []; // 控制果实成长速度、上浮速度的数组
    9. orange = new Image(); // 黄色果实
    10. blue = new Image(); // 蓝色果实
    11. constructor(){
    12. for (let i = 0; i < this.num; ++i) {
    13. this.alive[i] = true; // 先设置它的存活为 true
    14. this.diameter[i] = 0; // 未生长出来的果实半径为0
    15. this.speed[i] = Math.random() * 0.02 + 0.005; // 设置速度在区间 0.005 - 0.025 里
    16. this.orange.src = 'assets/img/fruit.png';
    17. this.blue.src = 'assets/img/blue.png';
    18. }
    19. // 绘制果实
    20. draw(){
    21. for (let i = 0; i < this.num; ++i) {
    22. // 只有属性为存活的时候才绘制
    23. if(this.alive[i]){
    24. if(this.diameter[i] <= 20) {
    25. this.diameter[i] += this.speed[i] * deltaTime; // 随着时间半径不断变大 也就是果实长大
    26. }else{
    27. this.y[i] -= this.speed[i] * deltaTime; // 果实成熟之后, y 坐标减小,果实开始上升
    28. }
    29. // 把果实绘制出来,为了让果实居中,所以要减去图片高度一半,宽度一半
    30. // 就像实现水平居中一样 left: 50px; margin-left: -(图片宽度 / 2);
    31. ctx_two.drawImage(this.orange, this.x[i] - this.diameter[i] / 2 , this.y[i] - this.diameter[i], this.diameter[i], this.diameter[i]);
    32. }
    33. if(this.y[i] <= -10) {
    34. this.alive[i] = false; // 果实出去了之后 存活状态为 flase
    35. }
    36. }
    37. }
    38. // 初始化果实的坐标
    39. born(i){
    40. let aneId = Math.floor( Math.random() * anemones.num ) // 随机拿到一个果实的 ID
    41. this.x[i] = anemones.x[aneId]; // 设置果实的 x 坐标为海葵的 x 坐标
    42. this.y[i] = cvs_height - anemones.height[aneId]; // 设置果实的 y 坐标,为海葵高度的顶点坐标
    43. }
    44. }