DynamicRefresh.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { _decorator, Node, Camera, Rect, UITransform, UIOpacity, view, Component } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('DynamicRefresh')
  4. export class DynamicRefresh extends Component {
  5. @property({ type: Camera, displayName: "渲染该节点的摄像机", visible: true })
  6. private _cur_camera: Camera = null;
  7. @property({ displayName: "裁剪时间间隔(秒)", visible() { return this._cur_camera ? true : false; } })
  8. private _cut_time = 0.1;
  9. @property({ displayName: "是否启用层级排序", visible: true })
  10. private _update_index = false;
  11. @property({ displayName: "层级排序间隔(秒)", visible() { return this._update_index ? true : false; } })
  12. private _update_time = 0.1;
  13. private _design_size = view.getDesignResolutionSize();
  14. private _cut_time_dt = 0;
  15. private _update_time_dt = 0;
  16. protected update(dt: number) {
  17. //节点排序
  18. if (this._update_index) {
  19. ++this._update_time_dt;
  20. if (this._update_time_dt >= this._update_time) {
  21. let children: Node[] = [];
  22. for (let child of this.node.children) {
  23. children.push(child);
  24. }
  25. children.sort((a: Node, b: Node) => {
  26. return b.position.y - a.position.y;
  27. });
  28. //如果将设置层级放到和角色是否在可视返回中有可能是角色范围判断错误
  29. let idx = 0
  30. for (let child of children) {
  31. child.setSiblingIndex(++idx);
  32. }
  33. this._update_time_dt = 0;
  34. }
  35. }
  36. //摄像机裁剪
  37. if (this._cur_camera) {
  38. this._cut_time_dt += dt;
  39. if (this._cut_time_dt >= this._cut_time) {
  40. let camera_rect = new Rect(this._cur_camera.node.position.x, this._cur_camera.node.position.y, this._design_size.width, this._design_size.height);
  41. for (let child of this.node.children) {
  42. let box = child.getComponent(UITransform).getBoundingBoxToWorld();
  43. (child.getComponent(UIOpacity) || child.addComponent(UIOpacity)).opacity = ((camera_rect.intersects(box) ? 255 : 0));
  44. }
  45. this._cut_time_dt = 0;
  46. }
  47. }
  48. }
  49. }