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

74 lines
2.3 KiB
TypeScript
Raw Normal View History

2024-02-28 03:25:11 -08:00
import {
_decorator,
2024-03-06 10:08:30 -08:00
AudioClip,
2024-02-28 03:25:11 -08:00
CCFloat,
Collider2D,
Component,
Contact2DType,
Director,
director,
EventTarget,
IPhysics2DContact,
RigidBody2D,
2024-03-06 10:08:30 -08:00
Vec2,
2024-02-28 03:25:11 -08:00
} from 'cc';
2024-03-06 07:10:31 -08:00
import IPoolable from '../Pool/IPoolable';
2024-03-06 10:08:30 -08:00
import { SoundManager } from '../Manager/SoundManager';
2024-02-27 18:19:33 -08:00
const { ccclass, property } = _decorator;
@ccclass('Ball')
2024-03-06 07:10:31 -08:00
export class Ball extends Component implements IPoolable {
2024-03-06 10:08:30 -08:00
@property({ type: CCFloat, visible: true })
private _maxSpeed: number;
@property({ type: RigidBody2D, visible: true })
private _rigidbody: RigidBody2D;
@property({ type: Collider2D, visible: true })
private _collider: Collider2D;
@property({ type: AudioClip, visible: true })
private _hitSound: AudioClip;
private _hitted = false;
2024-02-27 18:19:33 -08:00
public eventHitObstacle = new EventTarget();
public eventGoal = new EventTarget();
2024-02-28 03:25:11 -08:00
protected onLoad(): void {
2024-03-06 10:08:30 -08:00
if (this._collider) {
this._collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
this._collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
2024-02-27 18:19:33 -08:00
}
2024-02-28 03:25:11 -08:00
director.on(Director.EVENT_AFTER_PHYSICS, this.setMaxVelocity, this);
2024-02-27 18:19:33 -08:00
}
2024-03-06 10:08:30 -08:00
private onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
if (this._hitted) return;
this._hitted = true;
if (this._rigidbody.linearVelocity.length() >= 3) {
SoundManager.instance.playSfx(this._hitSound);
}
}
2024-02-28 03:25:11 -08:00
private setMaxVelocity() {
2024-03-06 10:08:30 -08:00
if (this._rigidbody.linearVelocity.length() > this._maxSpeed) {
this._rigidbody.linearVelocity = this._rigidbody.linearVelocity.normalize().multiplyScalar(this._maxSpeed);
2024-02-28 03:25:11 -08:00
}
2024-02-27 18:19:33 -08:00
}
private onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
// console.log(otherCollider.tag, otherCollider.node.name);
2024-03-06 10:08:30 -08:00
this._hitted = false;
2024-02-27 18:19:33 -08:00
}
2024-03-06 07:10:31 -08:00
2024-03-06 10:08:30 -08:00
public addFocre(force: Vec2) {
const point = this.node.getWorldPosition();
this._rigidbody.applyLinearImpulse(force, new Vec2(point.x, point.y), true);
2024-03-06 07:10:31 -08:00
}
2024-03-06 10:08:30 -08:00
reuse() {}
2024-03-06 07:10:31 -08:00
unuse() {
2024-03-06 10:08:30 -08:00
this._rigidbody.linearVelocity = Vec2.ZERO.clone();
this._rigidbody.angularVelocity = 0;
2024-03-06 07:10:31 -08:00
}
2024-02-28 03:25:11 -08:00
}