效果
思路
- 通过
cc.view
全局单例 View 对象获取屏幕尺寸 - 加载时根据屏幕尺寸动态计算上下左右边缘
代码实现
import { _decorator, Component, EventTouch, Input, input, Node, view } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('Player')
export class Player extends Component {private leftBound: number;private rightBound: number;private topBound: number;private bottomBound: number;protected onLoad(): void {this.initBound();input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);}initBound() {let height = view.getVisibleSize().height;let width = view.getVisibleSize().width;this.leftBound = -width / 2;this.rightBound = width / 2;this.bottomBound = -height / 2;this.topBound = height / 2;}protected onDestroy(): void {input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);}onTouchMove(event: EventTouch) {let posX = this.node.getPosition().x + event.getDeltaX();let posY = this.node.getPosition().y + event.getDeltaY();posX = Math.max(this.leftBound, posX);posX = Math.min(this.rightBound, posX);posY = Math.max(this.bottomBound, posY);posY = Math.min(this.topBound, posY);this.node.setPosition(posX, posY);}
}