Simple Collisions
Balls bounce around and collide with the walls, changing their color.
Click here to open project and view code
info
This demo is multiplayer! Try opening another browser tab to this page!
Code Samples
BallBehavior
This code makes the balls move and collide with the walls.
import {
Behavior,
Vector2,
EntityCollision,
SolidColor,
syncedValue,
ColoredPolygon,
} from "@dreamlab/engine";
export default class BallBehavior extends Behavior {
@syncedValue()
speed = 5.0;
private direction: Vector2 = new Vector2(0, 0);
onInitialize(): void {
// start with a random direction
this.direction = new Vector2(
Math.cos(Math.random() * Math.PI * 2),
Math.sin(Math.random() * Math.PI * 2)
).normalize();
this.listen(this.entity, EntityCollision, (e) => {
if (e.started) this.onCollide(e);
});
}
onTick(): void {
if (this.game.isClient()) return;
const movement = this.direction.mul((this.time.delta / 100) * this.speed);
this.entity.globalTransform.position =
this.entity.globalTransform.position.add(movement);
}
private onCollide(e: EntityCollision): void {
if (!e.other.name.includes("Wall")) return;
const wallName = e.other.name;
// change wall color to balls color
const wallSolidColor = e.other._.SolidColor;
wallSolidColor.cast(SolidColor).color =
this.entity._.ColoredPolygon.cast(ColoredPolygon).color;
// Bounce logic
if (wallName === "WallRight" || wallName === "WallLeft") {
this.direction.x *= -1;
} else if (wallName === "WallTop" || wallName === "WallBottom") {
this.direction.y *= -1;
}
}
}
Click here to clone project and view complete code and setup