- 果实上浮 (减小 y 轴坐标,让果实上浮)
我们需要思考一下逻辑。
随着时间变化,我们之前在 game-loop 文件里面有一个 deltaTime ,通过它我们来实现随时间变化。
修改你的 fruits.ts 文件
import { deltaTime } from "./game-loop";
class Fruits{
num: number = 30; // 绘画果实的数量
alive: boolean[] =[]; // 判断果实是否存活
x : number[]= []; // 果实的 x 坐标数组
y : number[] = []; // 果实的 y 坐标数组
diameter : number[] = []; // 果实的直径数组
speed: number[] = []; // 控制果实成长速度、上浮速度的数组
orange = new Image(); // 黄色果实
blue = new Image(); // 蓝色果实
constructor(){
for (let i = 0; i < this.num; ++i) {
this.alive[i] = true; // 先设置它的存活为 true
this.diameter[i] = 0; // 未生长出来的果实半径为0
this.speed[i] = Math.random() * 0.02 + 0.005; // 设置速度在区间 0.005 - 0.025 里
this.orange.src = 'assets/img/fruit.png';
this.blue.src = 'assets/img/blue.png';
}
// 绘制果实
draw(){
for (let i = 0; i < this.num; ++i) {
// 只有属性为存活的时候才绘制
if(this.alive[i]){
if(this.diameter[i] <= 20) {
this.diameter[i] += this.speed[i] * deltaTime; // 随着时间半径不断变大 也就是果实长大
}else{
this.y[i] -= this.speed[i] * deltaTime; // 果实成熟之后, y 坐标减小,果实开始上升
}
// 把果实绘制出来,为了让果实居中,所以要减去图片高度一半,宽度一半
// 就像实现水平居中一样 left: 50px; margin-left: -(图片宽度 / 2);
ctx_two.drawImage(this.orange, this.x[i] - this.diameter[i] / 2 , this.y[i] - this.diameter[i], this.diameter[i], this.diameter[i]);
}
if(this.y[i] <= -10) {
this.alive[i] = false; // 果实出去了之后 存活状态为 flase
}
}
}
// 初始化果实的坐标
born(i){
let aneId = Math.floor( Math.random() * anemones.num ) // 随机拿到一个果实的 ID
this.x[i] = anemones.x[aneId]; // 设置果实的 x 坐标为海葵的 x 坐标
this.y[i] = cvs_height - anemones.height[aneId]; // 设置果实的 y 坐标,为海葵高度的顶点坐标
}
}