CameraFitWidth.ts 826 B

12345678910111213141516171819202122232425262728
  1. import { _decorator, Component, Node, CameraComponent, view } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('CameraFitWidth')
  4. export class CameraFitWidth extends Component {
  5. private camera!:CameraComponent;
  6. private _defaultTanFov!: number;
  7. // LIFE-CYCLE CALLBACKS:
  8. onLoad () {
  9. this.camera = this.getComponent(CameraComponent);
  10. this._defaultTanFov = Math.tan(this.camera.fov / 180 * Math.PI);
  11. this.updateFov();
  12. window.addEventListener('resize', this.updateFov);
  13. }
  14. updateFov = () => {
  15. let tan2 = view.getVisibleSize().height / view.getDesignResolutionSize().height * this._defaultTanFov;
  16. this.camera.fov = Math.atan(tan2) / Math.PI * 180;
  17. }
  18. onDestroy() {
  19. window.removeEventListener('resize', this.updateFov);
  20. }
  21. }