import { _decorator, Component, EventTouch, Input, input, Node, quat, Quat, tween, Tween, Vec3 } from 'cc'; import { uiMgr } from '../core/manager/UIManager'; const { ccclass, property } = _decorator; @ccclass('ModelRotator') export class ModelRotator extends Component { @property({ tooltip: '初始旋转速度(度/秒)' }) speed: number = 45; @property({ tooltip: '触摸后的减速系数(0-1)' }) touchDeceleration: number = 0.95; @property({ tooltip: '斜角旋转的X轴角度(度)' }) tiltAngle: number = 36; // 改为36度斜角 // 新增Canvas节点引用 private canvasNode: Node = null!; private _targetQuat: Quat = quat(); private _currentSpeed: number = 0; private _touchStartX: number = 0; private _isDragging: boolean = false; private _baseRotation: Vec3 = new Vec3(); start() { this.canvasNode = this.node.parent.parent; // 设置斜角旋转(X轴36度 + Z轴旋转) this._baseRotation.set(this.tiltAngle, 0, -this.tiltAngle); // 增加Z轴倾斜 this.node.setRotationFromEuler(this._baseRotation); // 删除冗余的全局input监听 this.canvasNode.on(Node.EventType.TOUCH_START, this.onTouchStart, this); this.canvasNode.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this); this.canvasNode.on(Node.EventType.TOUCH_END, this.onTouchEnd, this); // 初始化自动旋转 this._currentSpeed = this.speed; this.startAutoRotation(); } startAutoRotation() { tween(this.node) .by(1, { //改为绕Z轴旋转 eulerAngles: new Vec3(this._currentSpeed, 0, -this._currentSpeed) }) .repeatForever() .start(); } onTouchMove(event: EventTouch) { if (!this._isDragging) return; // 改进差值计算方式 const currentX = event.getUILocation().x; const deltaX = currentX - this._touchStartX; this._touchStartX = currentX; // 改为同时更新Z轴旋转 const currentEuler = this.node.eulerAngles.clone(); currentEuler.z += deltaX * 0.5; // 绕Z轴旋转 this.node.setRotationFromEuler( new Vec3( this.tiltAngle, // 保持X轴斜角 0, // 固定Y轴 currentEuler.z // Z轴旋转 ) ); } onTouchStart(event: EventTouch) { this._touchStartX = event.getLocationX(); this._isDragging = true; this._currentSpeed = 0; // 停止自动旋转 Tween.stopAllByTarget(this.node); } onTouchEnd() { this._isDragging = false; // 添加惯性滑动效果 this._currentSpeed = this.speed * this.touchDeceleration; this.startAutoRotation(); } onDestroy() { //改为Canvas节点的事件解绑 if (this.canvasNode) { this.canvasNode.off(Node.EventType.TOUCH_START, this.onTouchStart, this); this.canvasNode.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this); this.canvasNode.off(Node.EventType.TOUCH_END, this.onTouchEnd, this); } } }