cocos-animator/animator-editor/assets/script/common/util/Tool.ts

125 lines
3.6 KiB
TypeScript
Raw Normal View History

2021-01-19 14:30:12 +00:00
/**
*
*/
export default class Tool {
/**
*
* @param arr
*/
public static randArray<T>(arr: Array<T>): T {
if (arr.length <= 0) {
return null;
}
return arr[this.randInt(0, arr.length - 1)];
}
/**
* [min, max]
* @param min
* @param max
*/
public static randInt(min: number, max: number) {
min = Math.ceil(min);
max = Math.floor(max);
if (min >= max) {
return max;
}
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* [min, max)
* @param min
* @param max
*/
public static randFloat(min: number, max: number) {
if (min >= max) {
return max;
}
return Math.random() * (max - min) + min;
}
/**
* value是否在 [min, max]
* @param min
* @param max
* @param value
* @param includeEdge min和max
*/
public static inRange(min: number, max: number, value: number, includeEdge: boolean = true) {
return includeEdge ? value >= min && value <= max : value > min && value < max;
}
/**
*
*/
public static arrayHas<T>(arr: T[], ele: T): boolean {
let idx = arr.findIndex((e) => { return e === ele; });
return idx >= 0;
}
/**
*
*/
public static arraySwap<T>(arr: T[], idx1: number, idx2: number) {
if (idx1 === idx2 || !this.inRange(0, arr.length - 1, idx1) || !this.inRange(0, arr.length - 1, idx2)) {
return;
}
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
}
/**
* fromIdx位置移到toIdx位置
*/
public static arrayMove<T>(arr: T[], fromIdx: number, toIdx: number) {
if (fromIdx === toIdx || !this.inRange(0, arr.length - 1, fromIdx) || !this.inRange(0, arr.length - 1, toIdx)) {
return;
}
let from: T[] = arr.splice(fromIdx, 1);
arr.splice(toIdx, 0, from[0]);
}
/**
*
* @param canRepeat false
* @returns
*/
public static arrayAdd<T>(arr: T[], ele: T, canRepeat: boolean = false): boolean {
if (!canRepeat && this.arrayHas(arr, ele)) {
return false;
}
arr.push(ele);
return true;
}
/**
*
* @returns
*/
public static arrayDelete<T>(arr: T[], ele: T): boolean {
let idx = arr.findIndex((e) => { return e === ele; });
if (idx === -1) {
return false;
}
arr.splice(idx, 1);
return true
}
/**
* widget组件
* @param node
* @param ignoreList
*/
public static updateWidget(node: cc.Node, ...ignoreList: cc.Node[]) {
node.children.forEach((c) => {
let widget = c.getComponent(cc.Widget);
widget && widget.updateAlignment();
if (this.arrayHas(ignoreList, c)) {
return;
}
this.updateWidget(c, ...ignoreList);
});
}
2021-01-19 14:30:12 +00:00
}