Files
esengine/source/src/Physics/Shapes/Circle.ts

64 lines
2.5 KiB
TypeScript
Raw Normal View History

2020-06-12 08:47:13 +08:00
///<reference path="./Shape.ts" />
class Circle extends Shape {
public radius: number;
private _originalRadius: number;
2020-06-16 00:04:28 +08:00
constructor(radius: number) {
2020-06-12 08:47:13 +08:00
super();
this.radius = radius;
this._originalRadius = radius;
}
public pointCollidesWithShape(point: Vector2): CollisionResult {
2020-06-16 00:04:28 +08:00
return ShapeCollisions.pointToCircle(point, this);
}
2020-06-16 00:04:28 +08:00
public collidesWithShape(other: Shape): CollisionResult {
if (other instanceof Box && (other as Box).isUnrotated) {
return ShapeCollisions.circleToBox(this, other);
}
2020-06-16 00:04:28 +08:00
if (other instanceof Circle) {
return ShapeCollisions.circleToCircle(this, other);
}
2020-06-16 00:04:28 +08:00
if (other instanceof Polygon) {
return ShapeCollisions.circleToPolygon(this, other);
}
throw new Error(`Collisions of Circle to ${other} are not supported`);
}
public recalculateBounds(collider: Collider) {
this.center = collider.localOffset;
2020-06-16 00:04:28 +08:00
if (collider.shouldColliderScaleAndRotationWithTransform) {
2020-06-29 15:41:02 +08:00
let scale = collider.entity.scale;
2020-06-16 00:04:28 +08:00
let hasUnitScale = scale.x == 1 && scale.y == 1;
let maxScale = Math.max(scale.x, scale.y);
this.radius = this._originalRadius * maxScale;
2020-06-29 15:41:02 +08:00
if (collider.entity.rotation != 0) {
2020-06-16 00:04:28 +08:00
let offsetAngle = Math.atan2(collider.localOffset.y, collider.localOffset.x) * MathHelper.Rad2Deg;
2020-06-29 15:41:02 +08:00
let offsetLength = hasUnitScale ? collider._localOffsetLength : (Vector2.multiply(collider.localOffset, collider.entity.scale)).length();
this.center = MathHelper.pointOnCirlce(Vector2.zero, offsetLength, MathHelper.toDegrees(collider.entity.rotation) + offsetAngle);
2020-06-16 00:04:28 +08:00
}
}
2020-06-29 15:41:02 +08:00
this.position = Vector2.add(collider.entity.position, this.center);
2020-06-16 00:04:28 +08:00
this.bounds = new Rectangle(this.position.x - this.radius, this.position.y - this.radius, this.radius * 2, this.radius * 2);
}
public overlaps(other: Shape){
if (other instanceof Box && (other as Box).isUnrotated)
return Collisions.isRectToCircle(other.bounds, this.position, this.radius);
if (other instanceof Circle)
return Collisions.isCircleToCircle(this.position, this.radius, other.position, (other as Circle).radius);
if (other instanceof Polygon)
return ShapeCollisions.circleToPolygon(this, other);
throw new Error(`overlaps of circle to ${other} are not supported`);
}
2020-06-12 08:47:13 +08:00
}