Skip to content

Commit

Permalink
feat: Transform origin and direction to account for level transformat…
Browse files Browse the repository at this point in the history
…ion (#404)
  • Loading branch information
mflerackers authored Sep 8, 2024
1 parent fb324db commit e0bd34a
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 3 deletions.
45 changes: 45 additions & 0 deletions examples/levelraycast.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
kaplay({
background: [31, 16, 42],
});

loadSprite("grass", "/sprites/grass.png");

const level = addLevel([
"===",
"= =",
"===",
], {
tileWidth: 64,
tileHeight: 64,
pos: vec2(256, 128),
tiles: {
"=": () => [
sprite("grass"),
area(),
],
},
});
level.use(rotate(45))

onLoad(() => {
level.spawn([
pos(
level.tileWidth() * 1.5,
level.tileHeight() * 1.5
),
circle(6),
color('#ea6262'),
{
add() {
const rayHit = level.raycast(
this.pos,
Vec2.fromAngle(0).scale(100)
);

debug.log(`${rayHit != null} ${rayHit && rayHit.object ? rayHit.object.id : -1}`);
},
},
])
})

debug.inspect = true
11 changes: 8 additions & 3 deletions src/game/level.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
vec2,
type Vec2Args,
} from "../math/math";
import { calcTransform } from "../math/various";
import type { CompList, GameObj, LevelComp, PathFindOpt } from "../types";
import { BinaryHeap } from "../utils";

Expand Down Expand Up @@ -351,6 +352,8 @@ export function addLevel(
}

obj.tilePos = p;
// Stale, so recalculate
obj.transform = calcTransform(obj);

if (spatialMap) {
insertIntoSpatialMap(obj);
Expand Down Expand Up @@ -412,7 +415,9 @@ export function addLevel(
return spatialMap![hash] || [];
},

raycast(origin: Vec2, direction: Vec2) {
raycast(this: GameObj<LevelComp | PosComp>, origin: Vec2, direction: Vec2) {
const worldOrigin = this.toWorld(origin);
const worldDirection = this.toWorld(origin.add(direction)).sub(worldOrigin);
const levelOrigin = origin.scale(
1 / this.tileWidth(),
1 / this.tileHeight(),
Expand All @@ -427,8 +432,8 @@ export function addLevel(
if (tile.is("area")) {
const shape = tile.worldArea();
const hit = shape.raycast(
origin,
direction,
worldOrigin,
worldDirection,
) as RaycastResult;
if (hit) {
if (minHit) {
Expand Down

0 comments on commit e0bd34a

Please sign in to comment.