-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmovementController.ts
63 lines (54 loc) · 2.43 KB
/
movementController.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { Ball, Cuboid, Shape, ShapeType, Vector2 } from "@dimforge/rapier2d-compat";
import { GameWorld, RapierPhysicsObject } from "./world";
import { add, Coordinate, MetersValue, mult } from "./utils";
export let debugData: {
rayCoodinate: Coordinate,
shape: Shape,
};
export function calculateMovement(physObject: RapierPhysicsObject, movement: Vector2, maxSteppy: MetersValue, world: GameWorld): Vector2 {
const currentTranslation = physObject.collider.translation();
const move = mult(add(
currentTranslation,
movement,
), { x: 1, y: 1 });
const {y: objHalfHeight, x: objHalfWidth } = (physObject.collider.shape as Cuboid).halfExtents;
// Get the extremity.
const rayCoodinate = new Coordinate(
move.x,
// Increase the bounds to the steppy position.
move.y - maxSteppy.value,
);
console.log(rayCoodinate.worldX, rayCoodinate.worldY);
// Increase by steppy amount.
const initialCollisionShape = new Cuboid(objHalfWidth, objHalfHeight - maxSteppy.value);
debugData = { rayCoodinate, shape: initialCollisionShape };
const collides = world.checkCollisionShape(rayCoodinate, initialCollisionShape, physObject.collider);
let canTravel = collides.length === 0;
// Pop the highest collider
const highestCollider = collides.sort((a,b) => a.collider.translation().y-b.collider.translation().y)[0];
// No collisions, go go go!
if (!highestCollider) {
return move;
}
const shape = highestCollider.collider.shape;
const bodyT = highestCollider.collider.translation();
if (currentTranslation.y - bodyT.y > maxSteppy.value) {
console.log('too big to steppy');
return currentTranslation;
}
// TODO: Support more types.
const halfHeight = shape.type === ShapeType.Cuboid ? (shape as Cuboid).halfExtents.y : (shape as Ball).radius;
// Step
const potentialX = bodyT.x;
// Crop a bit off the top to avoid colliding with it.
const potentialY = bodyT.y - halfHeight - objHalfHeight - 0.01;
// Check step is safe
debugData = { rayCoodinate: new Coordinate(potentialX, potentialY), shape: physObject.collider.shape }
if (world.checkCollisionShape(new Coordinate(potentialX, potentialY), physObject.collider.shape, physObject.collider).length){
console.log('step is not safe');
return currentTranslation;
}
move.y = potentialY;
move.x = potentialX;
return move;
}