feat: CircleShape

This commit is contained in:
cha0s 2019-04-12 23:51:40 -05:00
parent 90070840d6
commit 1f6551ae8c
4 changed files with 86 additions and 1 deletions

View File

@ -0,0 +1,48 @@
import {compose} from '@avocado/core';
import {Property} from '@avocado/mixins';
import {Shape} from './shape';
const decorate = compose(
Property('radius', {
track: true,
}),
);
export class CircleShape extends decorate(Shape) {
constructor() {
super();
this.on('radiusChanged', () => {
this.emit('aabbChanged');
});
}
get aabb() {
const [x, y] = this.position;
const halfRadius = this.radius / 2;
return [
x - halfRadius,
y - halfRadius,
x + halfRadius,
y + halfRadius,
];
}
fromJSON(json) {
super.fromJSON(json);
if (json.radius) {
this.radius = json.radius;
}
return this;
}
toJSON() {
return {
...super.toJSON(),
type: 'circle',
radius: this.radius,
}
}
}

View File

@ -3,6 +3,9 @@ export {BodyView} from './body-view';
import {PolygonShape} from './polygon';
export {PolygonShape};
import {CircleShape} from './circle';
export {CircleShape};
import {RectangleShape} from './rectangle';
export {RectangleShape};
@ -14,6 +17,9 @@ export {ShapeView} from './shape-view';
export function shapeFromJSON(json) {
let shape;
switch (json.type) {
case 'circle':
shape = new CircleShape();
break;
case 'list':
shape = new ShapeList();
break;

View File

@ -1,7 +1,12 @@
import {Composite, Bodies, Body as MatterBody, Vertices} from 'matter-js';
import {Vector} from '@avocado/math';
import {ShapeList, PolygonShape, RectangleShape} from '@avocado/physics';
import {
ShapeList,
CircleShape,
PolygonShape,
RectangleShape,
} from '@avocado/physics';
import {AbstractBody} from '../abstract/body';
@ -79,6 +84,14 @@ export class Body extends AbstractBody {
);
return [shape.position, body];
}
else if (shape instanceof CircleShape) {
const body = Bodies.circle(
0,
0,
shape.radius,
);
return [shape.position, body];
}
else if (shape instanceof PolygonShape) {
const vectors = [];
for (const vertice of shape) {

View File

@ -1,6 +1,7 @@
import {Color, Container, Primitives, Renderable} from '@avocado/graphics';
import {ShapeList} from './list';
import {CircleShape} from './circle';
import {PolygonShape} from './polygon';
export class ShapeView extends Renderable {
@ -15,6 +16,12 @@ export class ShapeView extends Renderable {
this.redrawPolygonLines();
});
}
if (shape instanceof CircleShape) {
this.redrawCircle();
shape.on('aabbChanged', () => {
this.redrawCircle();
});
}
if (shape instanceof ShapeList) {
for (const child of shape) {
const childShapeView = new ShapeView(child);
@ -31,6 +38,17 @@ export class ShapeView extends Renderable {
return this.container.internal;
}
redrawCircle() {
const primitives = new Primitives();
primitives.drawCircle(
this.shape.position,
this.shape.radius,
Primitives.lineStyle(new Color(255, 0, 255), 0.5),
);
this.container.removeAllChildren();
this.container.addChild(primitives);
}
redrawPolygonLines() {
const primitives = new Primitives();
let firstVertice;