pinball/assets/_Game/Scripts/Gameplay/Flipper.ts

128 lines
3.7 KiB
TypeScript

import {
_decorator,
Component,
HingeJoint2D,
input,
CCFloat,
Input,
EventKeyboard,
KeyCode,
Enum,
Animation,
Vec3,
AnimationState,
} from 'cc';
import { EventManger } from '../Manager/EventManger';
import GameEvent from '../Events/GameEvent';
import TimeConfig from '../Enum/TimeConfig';
const { ccclass, property } = _decorator;
export enum ControllerSide {
Left,
Right,
}
Enum(ControllerSide);
@ccclass('Flipper')
export class Flipper extends Component {
@property({ type: Animation, visible: true })
private _animation: Animation;
@property({ visible: true, type: HingeJoint2D })
private _hingeJoint: HingeJoint2D;
@property({ visible: true, type: CCFloat })
private _motorSpeedActive: number;
@property({ visible: true, type: CCFloat })
private _motorSpeedDeActive: number;
@property({ visible: true, type: ControllerSide })
private side = ControllerSide.Left;
private _timer = 0;
private _isAnimationPlaying;
protected onLoad(): void {
input.on(Input.EventType.KEY_DOWN, this.onKeyInputDown, this);
input.on(Input.EventType.KEY_UP, this.onKeyInputUp, this);
EventManger.instance.on(GameEvent.ControlTouchStart, this.onTouchStart, this);
EventManger.instance.on(GameEvent.ControlTouchEnd, this.onTouchEnd, this);
}
protected start(): void {
this._animation.play();
}
protected update(dt: number): void {
this._timer += dt;
this._isAnimationPlaying = this._animation.getState(this._animation.defaultClip.name).isPlaying;
if (!this._isAnimationPlaying && this._timer >= TimeConfig.Tutorial) {
this._animation.play();
}
}
//#region Input Handler
private onKeyInputDown(event: EventKeyboard) {
switch (event.keyCode) {
case KeyCode.KEY_A:
case KeyCode.ARROW_LEFT:
if (this.side == ControllerSide.Left) this.activeFlipper();
this._timer = 0;
if (this._animation.getState(this._animation.defaultClip.name).isPlaying) {
this._animation.stop();
}
break;
case KeyCode.KEY_D:
case KeyCode.ARROW_RIGHT:
if (this.side == ControllerSide.Right) this.activeFlipper();
this._timer = 0;
if (this._isAnimationPlaying) {
this._animation.stop();
}
break;
default:
break;
}
}
private onKeyInputUp(event: EventKeyboard) {
switch (event.keyCode) {
case KeyCode.KEY_A:
case KeyCode.ARROW_LEFT:
if (this.side == ControllerSide.Left) this.deActiveFlipper();
break;
case KeyCode.KEY_D:
case KeyCode.ARROW_RIGHT:
if (this.side == ControllerSide.Right) this.deActiveFlipper();
break;
default:
break;
}
}
private onTouchStart(controllerSide: ControllerSide) {
if (this.side == controllerSide) {
this.activeFlipper();
}
this.node.setScale(Vec3.ONE);
this._timer = 0;
if (this._isAnimationPlaying) {
this._animation.stop();
}
}
private onTouchEnd(controllerSide: ControllerSide) {
if (this.side == controllerSide) {
this.deActiveFlipper();
}
}
//#endregion
private activeFlipper(): void {
this._hingeJoint.motorSpeed = this._motorSpeedActive;
}
private deActiveFlipper(): void {
this._hingeJoint.motorSpeed = this._motorSpeedDeActive;
}
}