果实长大,那么它的直径应该是随着时间变大的,当长大到一定的直径就停止生长,然后开始上浮,上浮的过程中,我们需要不同的速度,所以我们需要一个存放速度的数组,同时它也可以限定生长速度。
import { cvs_height, ctx_two, anemones } from "./init";
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.born(i);
}
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);
// 第一个参数 图片, 第二三个参数,坐标轴的 x 和 y,第四五个参数,图片的宽高
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 坐标,为海葵高度的顶点坐标
}
}
export default Fruits;