pinball/assets/_Game/Scripts/Environments/DamageableObject.ts

58 lines
2.1 KiB
TypeScript

import { _decorator, CCFloat, CCInteger, Collider2D, Color, Component, Contact2DType, Sprite, Vec3 } from 'cc';
import { GameManager } from '../Manager/GameManager';
const { ccclass, property, float } = _decorator;
@ccclass('DamageableObject')
export class DamageableObject extends Component {
@property({ type: Collider2D, visible: true })
private _collider: Collider2D;
@property({ type: Sprite, visible: true })
private _sprite: Sprite;
@property({ type: CCInteger, visible: true })
private _score: number;
@property({ type: CCFloat, visible: true })
private _flySpeed: number;
private _flyDirection: Vec3;
private _targetColor: Color;
private _hitted = false;
protected onLoad(): void {
this._collider.on(Contact2DType.BEGIN_CONTACT, this.onContactBegin, this);
}
protected update(dt: number): void {
if (this._hitted) {
const pos = new Vec3();
Vec3.multiplyScalar(pos, this._flyDirection, this._flySpeed * dt);
this.node.worldPosition = this.node.getWorldPosition().add(pos);
const scale = new Vec3();
Vec3.multiplyScalar(scale, Vec3.ONE.clone(), 0.5 * dt);
this.node.scale = this.node.getScale().add(scale);
this.node.angle += 800 * dt;
this._sprite.color = this._sprite.color.clone().lerp(this._targetColor, 2 * dt);
if (this._sprite.color.a == 0) {
}
}
}
private onContactBegin(selfCollider: Collider2D, otherCollider: Collider2D) {
if (this._hitted) return;
this._collider.enabled = false;
let center = this.node.getWorldPosition();
let other = otherCollider.node.getWorldPosition();
this._flyDirection = center.subtract(other);
this._flyDirection.normalize();
this._hitted = true;
this._targetColor = this._sprite.color.clone();
this._targetColor.a = 0;
this.node.setSiblingIndex(this.node.parent.children.length - 1);
if (this._score > 0) {
GameManager.instance.destroyEnviromentsObject(this._score);
}
}
}