Skip to content

Commit

Permalink
feat: Add GraphicsComponent.bounds which will return the world bounds…
Browse files Browse the repository at this point in the history
… of the current graphic if applicable, local otherwise
  • Loading branch information
eonarheim committed Feb 29, 2024
1 parent f0f23fd commit 7e1e237
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ This project adheres to [Semantic Versioning](http://semver.org/).

### Added

-
- Added `GraphicsComponent.bounds` which will report the world bounds of the graphic if applicable!

### Fixed

Expand Down
18 changes: 18 additions & 0 deletions src/engine/Graphics/GraphicsComponent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Component } from '../EntityComponentSystem/Component';
import { Material } from './Context/material';
import { Logger } from '../Util/Log';
import { WatchVector } from '../Math/watch-vector';
import { TransformComponent } from '../EntityComponentSystem';

/**
* Type guard for checking if a Graphic HasTick (used for graphics that change over time like animations)
Expand Down Expand Up @@ -362,13 +363,30 @@ export class GraphicsComponent extends Component {
this._localBounds = bb;
}

/**
* Get local bounds of graphics component
*/
public get localBounds(): BoundingBox {
if (!this._localBounds || this._localBounds.hasZeroDimensions()) {
this.recalculateBounds();
}
return this._localBounds;
}

/**
* Get world bounds of graphics component
*/
public get bounds(): BoundingBox {
let bounds = this.localBounds;
if (this.owner) {
const tx = this.owner.get(TransformComponent);
if (tx) {
bounds = bounds.transform(tx.get().matrix);
}
}
return bounds;
}

/**
* Update underlying graphics if necessary, called internally
* @param elapsed
Expand Down
21 changes: 21 additions & 0 deletions src/spec/GraphicsComponentSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,27 @@ describe('A Graphics ECS Component', () => {
}));
});

it('correctly calculates graphics world bounds (rasters)', () => {
const tx = new ex.TransformComponent();
tx.pos = ex.vec(500, 900);
const sut = new ex.GraphicsComponent();
const rec2 = new ex.Rectangle({
width: 200,
height: 10
});
rec2.scale = ex.vec(2, 2);
sut.add(rec2);

const entity = new ex.Entity([tx, sut]);

expect(sut.bounds).toEqual(new ex.BoundingBox({
left: 300,
right: 700,
top: 890,
bottom: 910
}));
});

it('correctly calculates graphics bounds (rasters + offset)', () => {
const sut = new ex.GraphicsComponent();
const rec2 = new ex.Rectangle({
Expand Down

0 comments on commit 7e1e237

Please sign in to comment.