51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
import {
|
|
_decorator,
|
|
CCFloat,
|
|
Collider2D,
|
|
Component,
|
|
Contact2DType,
|
|
Director,
|
|
director,
|
|
EventTarget,
|
|
IPhysics2DContact,
|
|
RigidBody2D,
|
|
} from 'cc';
|
|
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;
|
|
private hitted = false;
|
|
|
|
public eventHitObstacle = new EventTarget();
|
|
public eventGoal = new EventTarget();
|
|
|
|
protected onLoad(): void {
|
|
if (this.getComponent(Collider2D)) {
|
|
this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
|
|
this.collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
|
|
}
|
|
|
|
director.on(Director.EVENT_AFTER_PHYSICS, this.setMaxVelocity, this);
|
|
}
|
|
|
|
private onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {}
|
|
|
|
private setMaxVelocity() {
|
|
if (this.rigidbody.linearVelocity.length() > this.maxSpeed) {
|
|
this.rigidbody.linearVelocity = this.rigidbody.linearVelocity.normalize().multiplyScalar(this.maxSpeed);
|
|
}
|
|
}
|
|
|
|
private onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
|
|
// console.log(otherCollider.tag, otherCollider.node.name);
|
|
this.hitted = false;
|
|
}
|
|
}
|