Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: YSortComponent #3057

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,29 @@ This project adheres to [Semantic Versioning](http://semver.org/).
- Built in actions now have a unique `id` property
- create development builds of excalibur that bundlers can use in dev mode
- show warning in development when Entity hasn't been added to a scene after a few seconds
- YSortComponent that adjusts z-index based on its global Y position. This can be used on an
Actor with the new `ySort` configuration in the constructor, or added as a component to an Entity.

```ts
new ex.Actor({
ySort: true,

// or

ySort: {
offset: 0, // apply an offset to the resulting z-index
order: 1 // 1 will add the pos.y to the z-index, -1 will subtract it
}
});

// or
entity.addComponent(
new ex.YSortComponent({
offset: 0,
order: 1
})
);
```

### Fixed

Expand Down
1 change: 1 addition & 0 deletions sandbox/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
<li><a href="tests/tilemap/tilemap.html">TileMap</a></li>
<li><a href="tests/pointer/index.html">Pointer event propagation</a></li>
<li><a href="tests/screen/index.html">Screen Fit Container</a></li>
<li><a href="tests/ysort/index.html">YSortComponent</a></li>
</ul>

<h3>Engine</h3>
Expand Down
14 changes: 14 additions & 0 deletions sandbox/tests/ysort/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>YSortComponent</title>
</head>
<body>
<p>Should sort z-index based on pos.y value</p>
<script src="../../lib/excalibur.js"></script>
<script src="ysort/ysort.js"></script>
</body>
</html>
61 changes: 61 additions & 0 deletions sandbox/tests/ysort/ysort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/// <reference path='../../lib/excalibur.d.ts' />

var game = new ex.Engine({
width: 800,
height: 600
});

const ySort = { order: 1 };

const blue = new ex.Actor({
pos: ex.vec(100, 100),
width: 100,
height: 100,
color: ex.Color.Blue,
ySort
});

const red = new ex.Actor({
pos: ex.vec(100, 90),
width: 100,
height: 100,
color: ex.Color.Red,
ySort
});

const green = new ex.Actor({
pos: ex.vec(100, 111),
width: 100,
height: 100,
color: ex.Color.Green,
ySort
});

const orange = new ex.Actor({
pos: ex.vec(150, 114),
width: 100,
height: 100,
color: ex.Color.Orange,
ySort
});

const yellow = new ex.Actor({
pos: ex.vec(100, 80),
width: 100,
height: 100,
color: ex.Color.Yellow,
ySort: { ...ySort, offset: 0 }
});

yellow.actions.repeatForever((ctx) => ctx.moveBy(0, 100, 25).moveBy(0, -100, 25));

game.add(blue);
game.add(red);
game.add(green);
game.add(orange);
game.add(yellow);
game.start();

yellow.on('postupdate', () => {
console.log('y:', Math.round(yellow.pos.y), 'z:', yellow.z);
});
20 changes: 18 additions & 2 deletions src/engine/Actor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ import { Raster } from './Graphics/Raster';
import { Text } from './Graphics/Text';
import { CoordPlane } from './Math/coord-plane';
import { EventEmitter, EventKey, Handler, Subscription } from './EventEmitter';
import { Component } from './EntityComponentSystem';
import { Component, YSortComponent, YSortOptions } from './EntityComponentSystem';

/**
* Type guard for checking if something is an Actor
Expand Down Expand Up @@ -138,6 +138,10 @@ export interface ActorArgs {
* Optionally set the anchor for graphics in the actor
*/
offset?: Vector;
/**
* Optionally set the ySort options for the actor
*/
ySort?: true | YSortOptions;
/**
* Optionally set the collision type
*/
Expand Down Expand Up @@ -272,6 +276,12 @@ export class Actor extends Entity implements Eventable, PointerEvents, CanInitia
*/
public actions: ActionsComponent;

/**
* Access to the Actor's built in [[YSortComponent]] if `ySort` was configured
* in the constructor
*/
public ySort: YSortComponent;

/**
* Gets the position vector of the actor in pixels
*/
Expand Down Expand Up @@ -554,7 +564,8 @@ export class Actor extends Entity implements Eventable, PointerEvents, CanInitia
anchor,
offset,
collisionType,
collisionGroup
collisionGroup,
ySort
} = {
...config
};
Expand Down Expand Up @@ -633,6 +644,11 @@ export class Actor extends Entity implements Eventable, PointerEvents, CanInitia
);
}
}

if (ySort) {
this.ySort = new YSortComponent(typeof ySort === 'object' ? ySort : {});
this.addComponent(this.ySort);
}
}

public clone(): Actor {
Expand Down
10 changes: 9 additions & 1 deletion src/engine/Collision/MotionSystem.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Entity, Query, SystemPriority, World } from '../EntityComponentSystem';
import { Entity, Query, SystemPriority, World, YSortComponent } from '../EntityComponentSystem';
import { MotionComponent } from '../EntityComponentSystem/Components/MotionComponent';
import { TransformComponent } from '../EntityComponentSystem/Components/TransformComponent';
import { System, SystemType } from '../EntityComponentSystem/System';
Expand All @@ -24,10 +24,13 @@ export class MotionSystem extends System {
update(elapsedMs: number): void {
let transform: TransformComponent;
let motion: MotionComponent;
let ySort: YSortComponent;

const entities = this.query.entities;
for (let i = 0; i < entities.length; i++) {
transform = entities[i].get(TransformComponent);
motion = entities[i].get(MotionComponent);
ySort = entities[i].get(YSortComponent);

const optionalBody = entities[i].get(BodyComponent);
if (this._physicsConfigDirty && optionalBody) {
Expand All @@ -51,6 +54,11 @@ export class MotionSystem extends System {

// Update transform and motion based on Euler linear algebra
EulerIntegrator.integrate(transform, motion, totalAcc, elapsedMs);

// Update z index based on y position
if (ySort) {
ySort.updateZ();
}
}
this._physicsConfigDirty = false;
}
Expand Down
49 changes: 49 additions & 0 deletions src/engine/EntityComponentSystem/Components/YSortComponent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Component } from '../Component';
import { TransformComponent } from './TransformComponent';

/**
* Adjusts the z-index of an entity based on its global y position
*/
export interface YSortOptions {
/**
* Applies an offset to the resulting z-index
* @default 0
*/
offset?: number;

/**
* When 1, the z-index will increase as the y value increases. When -1, the
* z-index will decrease as the y value increases.
* @default 1
*/
order?: 1 | -1;
}

export class YSortComponent extends Component {
offset: number;
order: number;

constructor(public options: YSortOptions = {}) {
super();
this.offset = options.offset ?? 0;
this.order = options.order ?? 1;
}

private get _transform() {
const transform = this.owner?.get(TransformComponent);

if (!transform) {
throw new Error('YSortComponent requires a TransformComponent');
}

return transform;
}

public updateZ() {
const y = this._transform.globalPos.y;
const rounded = Math.floor(y) * this.order;
const z = rounded + this.offset;

this._transform.z = z;
}
}
1 change: 1 addition & 0 deletions src/engine/EntityComponentSystem/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ export * from './Priority';

export * from './Components/TransformComponent';
export * from './Components/MotionComponent';
export * from './Components/YSortComponent';
65 changes: 65 additions & 0 deletions src/spec/YSortComponentSpec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import * as ex from '@excalibur';
import { ExcaliburMatchers } from 'excalibur-jasmine';

describe('A YSortComponent', () => {
beforeAll(() => {
jasmine.addMatchers(ExcaliburMatchers);
});

it('exists', () => {
expect(ex.YSortComponent).toBeDefined();
});

it('can be constructed', () => {
const ysort = new ex.YSortComponent();
expect(ysort).toBeDefined();
});

it('sets all options in constructor', () => {
const ysort = new ex.YSortComponent({
offset: 10,
order: -1
});
expect(ysort.offset).toBe(10);
expect(ysort.order).toBe(-1);
});

it('sets the z-index based on transform.y', () => {
const entity = new ex.Entity();
const transform = new ex.TransformComponent();
const ysort = new ex.YSortComponent();

entity.addComponent(transform);
entity.addComponent(ysort);
transform.pos = ex.vec(10, 42);

ysort.updateZ();
expect(transform.z).toBe(42);
});

it('orders in descending order', () => {
const entity = new ex.Entity();
const transform = new ex.TransformComponent();
const ysort = new ex.YSortComponent({ order: -1 });

entity.addComponent(transform);
entity.addComponent(ysort);
transform.pos = ex.vec(10, 42);

ysort.updateZ();
expect(transform.z).toBe(-42);
});

it('applies an offset', () => {
const entity = new ex.Entity();
const transform = new ex.TransformComponent();
const ysort = new ex.YSortComponent({ offset: 10 });

entity.addComponent(transform);
entity.addComponent(ysort);
transform.pos = ex.vec(10, 42);

ysort.updateZ();
expect(transform.z).toBe(52);
});
});
Loading