打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
实现精灵边移动边切换图片的效果

// 假设你有一个精灵节点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);

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
游戏开发者如何应用 CocosCreator 技术? | 技术头条
Unity新功能Sprite Atlas与Sprite Mask详解
为了女朋友!熬夜撸了一个“合成大西瓜”!(附源码)
CSS Sprite (CSS精灵)
cocos2d-x总结(五)CCSprite精灵的加载与常用操作
Cocos2d
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服