cocos creator switch按钮

2023-01-26

使用tween动画

代码如下

import { _decorator, Component, Node, tween, Vec3, UITransform } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('SwitchController')
export class SwitchController extends Component {
    @property(Node)
    SwitchButton:Node = null;
    @property(Node)
    Off:Node = null;
    @property(Node)
    On:Node = null;
    @property(Node)
    Switch:Node = null;
    @property(Boolean)
    SwitchFlag:Boolean = true;

    radius = 0;
    radiusSwitch = 0;

    onLoad(){
        this.radius = this.SwitchButton.getComponent(UITransform).contentSize.width;
        this.radiusSwitch = this.SwitchButton.getComponent(UITransform).contentSize.width/2;

        this.switchHandle();
        this.SwitchButton.on(Node.EventType.TOUCH_END,()=>{
            this.SwitchFlag = !this.SwitchFlag;      
            this.switchHandle();
        })
    }

    switchHandle(){
        if(!this.SwitchFlag){
            tween(this.Off)
            .to(0.3, {position: new Vec3(this.SwitchButton.position.x,this.Off.position.y, 10)})
            .start();
            tween(this.Switch)
            .to(0.3, {position: new Vec3(this.radiusSwitch,this.On.position.y, 10)})
            .start();
            tween(this.On)
            .to(0.3, {position: new Vec3(this.radius,this.On.position.y, 0)})
            .start();
        }else{
            tween(this.On)
            .to(0.3, {position: new Vec3(this.SwitchButton.position.x,this.On.position.y, 10)})
            .start();

            tween(this.Switch)
            .to(0.3, {position: new Vec3(-this.radiusSwitch,this.On.position.y, 10)})
            .start();
            
            tween(this.Off)
            .to(0.3, {position: new Vec3(-this.radius,this.Off.position.y, 0)})
            .start()
        }
    }

    start() {

    }

    update(deltaTime: number) {
        
    }
}

 

原贴地址: https://blog.csdn.net/mingketao/article/details/127733002