pinball/assets/_Game/Scripts/Utilities/index.ts

58 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-03-26 20:04:28 -07:00
import { Vec2, Vec3 } from 'cc';
2024-02-28 03:25:11 -08:00
export default class Utilities {
2024-03-03 00:23:29 -08:00
/**
*
2024-03-12 01:50:54 -07:00
* @param time (s)
2024-03-03 00:23:29 -08:00
* @returns
*/
2024-02-28 03:25:11 -08:00
public static delay(time: number): Promise<any> {
2024-03-12 01:50:54 -07:00
return new Promise((resolve) => setTimeout(resolve, time * 1000));
2024-02-28 03:25:11 -08:00
}
2024-03-07 09:45:13 -08:00
/**
*@param predicate
2024-03-12 01:50:54 -07:00
* @param time (s)
2024-03-07 09:45:13 -08:00
* @returns
*/
2024-03-12 01:50:54 -07:00
public static async waitUntil(predicate: () => boolean, timeCheck = 0.01) {
2024-03-07 09:45:13 -08:00
while (!predicate()) {
await this.delay(timeCheck);
}
}
2024-02-28 03:25:11 -08:00
public static getJson(json: string): any {
try {
return JSON.parse(json);
} catch (error) {
return false;
}
}
2024-03-12 01:50:54 -07:00
2024-03-26 20:04:28 -07:00
public static Vec2ToVec3(Vec2: Vec2): Vec3 {
return new Vec3(Vec2.x, Vec2.y);
}
public static Vec3ToVec2(Vec3: Vec3): Vec2 {
return new Vec2(Vec3.x, Vec3.y);
}
public static weightedRandom<T>(items: T[], weights: number[]): T {
2024-03-12 01:50:54 -07:00
const weightsClone = [...weights];
2024-03-26 20:04:28 -07:00
const totalWeight = weightsClone.reduce((a, b) => a + b, 0);
let random = Math.random() * totalWeight;
const item = items.find((_, i) => (random -= weightsClone[i]) <= 0);
return item;
// for (i = 1; i < weightsClone.length; i++) {
// weightsClone[i] += weights[i - 1];
// }
2024-03-12 01:50:54 -07:00
2024-03-26 20:04:28 -07:00
// let random = Math.random() * weightsClone[weightsClone.length - 1];
2024-03-12 01:50:54 -07:00
2024-03-26 20:04:28 -07:00
// for (i = 0; i < weightsClone.length; i++) {
// if (weightsClone[i] > random) break;
// }
// return [items[i], i];
2024-03-12 01:50:54 -07:00
}
2024-02-28 03:25:11 -08:00
}