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

51 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-02-28 03:25:11 -08:00
import {
_decorator,
CCFloat,
Collider2D,
Component,
Contact2DType,
Director,
director,
EventTarget,
IPhysics2DContact,
RigidBody2D,
} from 'cc';
2024-02-27 18:19:33 -08:00
const { ccclass, property } = _decorator;
@ccclass('Ball')
export class Ball extends Component {
@property({ visible: true, type: CCFloat })
public maxSpeed: number;
@property({ visible: true, type: RigidBody2D })
public rigidbody: RigidBody2D;
@property(Collider2D)
public collider: Collider2D;
public isActive: boolean;
2024-03-01 03:08:57 -08:00
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-02-27 18:19:33 -08:00
if (this.getComponent(Collider2D)) {
this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
this.collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
}
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 01:28:01 -08:00
private onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {}
2024-02-28 03:25:11 -08:00
private setMaxVelocity() {
if (this.rigidbody.linearVelocity.length() > this.maxSpeed) {
this.rigidbody.linearVelocity = this.rigidbody.linearVelocity.normalize().multiplyScalar(this.maxSpeed);
}
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-01 03:08:57 -08:00
this.hitted = false;
2024-02-27 18:19:33 -08:00
}
2024-02-28 03:25:11 -08:00
}