// 假设你有一个精灵节点sprite // 你可以给它添加一个脚本组件,比如叫做TouchChange // 在TouchChange.ts文件中,你可以这样写 import { _decorator, Component, Node, Sprite, SpriteFrame } from 'cc'; const { ccclass, property } = _decorator; @ccclass('TouchChange') export class TouchChange extends Component { // 用来存放10张图片的SpriteFrame数组 @property(SpriteFrame) frames: SpriteFrame[] = []; // 用来获取当前节点的Sprite组件 private sprite: Sprite | null = null; // 用来记录当前显示的图片索引 private index: number = 0; // 在start方法中,初始化Sprite组件和索引值 start () { this.sprite = this.node.getComponent(Sprite); if (this.sprite) { this.index = this.frames.indexOf(this.sprite.spriteFrame); } } // 在onLoad方法中,注册触摸事件的回调函数 onLoad () { this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this); } // 在onDestroy方法中,取消注册触摸事件的回调函数 onDestroy () { this.node.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this); } // 在onTouchMove方法中,根据触摸移动的方向切换图片 onTouchMove (event) { if (this.sprite) { // 获取触摸移动的距离 let delta = event.getDelta(); // 如果向上移动超过10像素,则显示下一张图片(循环) if (delta.y > 10) { this.index++; if (this.index >= this.frames.length) { this.index = 0; } this.sprite.spriteFrame = this.frames[this.index]; } // 如果向下移动超过10像素,则显示上一张图片(循环) else if (delta.y < -10) { this.index--; if (this.index < 0) { this.index = this.frames.length - 1; } this.sprite.spriteFrame = this.frames[this.index]; } } // 移动节点到触摸位置(可选) let position = event.getLocation(); position.x -= cc.winSize.width / 2; position.y -= cc.winSize.height / 2; position.z = 0; let newPosition = new Vec3(position.x, position.y); let oldPosition = new Vec3(this.node.position.x,this.node.position.y); var moveAction= cc.moveTo(1,newPosition); var rotateAction= cc.rotateBy(1,-360); var spawnAction= cc.spawn(moveAction ,rotateAction); var repeatAction= cc.repeat(spawnAction ,1); var action= repeatAction; action.setTag(1); node.stopAllActions(); node.runAction(action);
联系客服