utils.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. export namespace Utils {
  2. export function str2arr(str: string, char: string){
  3. return str.split(char);
  4. }
  5. export function createNode(parent: cc.Node, name: string = ''){
  6. let node = new cc.Node(name);
  7. parent.addChild(node);
  8. return node;
  9. }
  10. export function intDefault(data, def: number = 0){
  11. if(data == '') return 0;
  12. return Number(data);
  13. }
  14. // 角度转弧度
  15. export function radian(degree: number){
  16. return degree * (Math.PI/180);
  17. }
  18. export function degree(radian: number){
  19. return radian * (180/Math.PI);
  20. }
  21. export function getCpt<T extends cc.Component>(cpt: {new(): T}, node: cc.Node): T{
  22. let moveCpt = node.getComponent(cpt);
  23. if(!moveCpt) {
  24. moveCpt = node.addComponent(cpt);
  25. }
  26. return moveCpt;
  27. }
  28. export function addFullWidget(node: cc.Node){
  29. let widget = node.addComponent(cc.Widget);
  30. widget.isAlignBottom = true;
  31. widget.isAlignTop = true;
  32. widget.isAlignLeft = true;
  33. widget.isAlignRight = true;
  34. widget.left = 0;
  35. widget.right = 0;
  36. widget.top = 0;
  37. widget.bottom = 0;
  38. }
  39. export function strReplaceSeparator(str:string){
  40. return str.replace(/\;|\;/g, ',');
  41. }
  42. export function strToJson(str: string): any{
  43. let jsonStr = strReplaceSeparator(str)
  44. jsonStr = jsonStr.replace(/\]\[/g, '],[');
  45. return JSON.parse(jsonStr);
  46. }
  47. export function pos2vec2(pos: string): cc.Vec2 {
  48. let posJson = Utils.strToJson(pos);
  49. return cc.v2(Number(posJson[0]), -Number(posJson[1]));
  50. }
  51. export function getAniExtent(state: cc.AnimationState){
  52. // let cur = state.curves;
  53. let extent = 0;
  54. for (let index = 0; index < state.curves.length; index++) {
  55. const element = state.curves[index];
  56. if(element.prop == 'position') {
  57. let values = element.values as cc.Vec3[];
  58. for (let index = 1; index < values.length; index++) {
  59. extent += values[index].sub(values[index-1]).mag();
  60. }
  61. }
  62. if(element.prop == 'y' || element.prop == 'x') {
  63. let values = element.values as number[];
  64. for (let index = 1; index < values.length; index++) {
  65. extent += Math.abs(values[index] - values[index-1]);
  66. }
  67. }
  68. }
  69. return extent;
  70. }
  71. }