super-hero/assets/cc-common/cc-ui/UmSwitchButton.ts

68 lines
2.1 KiB
TypeScript

import { _decorator, Button, CCFloat, Color, Label, Node, Sprite, SpriteFrame, tween, Vec3 } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('UmSwitchButton')
export class UmSwitchButton extends Button {
@property(CCFloat) public animTime = 0.1;
@property(Sprite) public dot: Sprite = null!;
@property(Label) public title: Label = null!;
@property(SpriteFrame) public spf_off: SpriteFrame = null!;
@property(SpriteFrame) public spf_on: SpriteFrame = null!;
@property(SpriteFrame) public spf_dot_off: SpriteFrame = null!;
@property(SpriteFrame) public spf_dot_on: SpriteFrame = null!;
@property(Node) public listTargetPos: Node[] = [];
public status: boolean = true;
public onSwitched: ((status: boolean) => void) | undefined;
setInitStatus(status: boolean) {
this.status = status;
this.dot.node.position = this.getDotTarget(this.status);
this.setSpriteFrame(status);
}
onClicked(btn: Button) {
this.interactable = false;
this.status = !this.status;
tween(this.dot.node).to(this.animTime, { position: this.getDotTarget(this.status) }).call(() => {
this.interactable = true;
this.setSpriteFrame(this.status);
}).start();
this.onSwitched?.(this.status);
}
getDotTarget(status: boolean): Vec3 {
return status ? this.listTargetPos[1].position : this.listTargetPos[0].position;
}
setSpriteFrame(status: boolean) {
if (status) {
this.normalSprite = this.spf_on;
this.dot.spriteFrame = this.spf_dot_on;
this.title.string = "ON";
this.title.node.setPositionX(-20.5);
this.title.setColor(new Color(83, 251, 255));
}
else {
this.normalSprite = this.spf_off;
this.dot.spriteFrame = this.spf_dot_off;
this.title.string = "OFF";
this.title.node.setPositionX(20.5);
this.title.setColor(new Color(105, 119, 150));
}
}
public updateTitle() {
this.title.string = this.status ? "ON" : "OFF";
}
}