Pathfinding
In the Actor example, we assigned some logic to a robot so it would continually
move, changing direction when it bumped into a wall. This example is more simple
because we don't have to create any logic for the robot, instead we will control
the robots movement with a mouse click / screen touch. Our WorldDescriptor is the
same as before, so we won't repeat it here, but the createDroid function is more
simple.
async function createDroid(context, position) {
const graphicsDescriptor = {
spriteSheetName: "demos/graphics/png/levitate-droid",
spriteWidth: 58,
spriteHeight: 107,
columnDirections: [
WT.Direction.West,
WT.Direction.South,
WT.Direction.East,
WT.Direction.North,
],
numFrames: 1,
};
const graphics = await WT.createDirectionalGraphics(graphicsDescriptor, context);
const dimensions = WT.TwoByOneIsometric.getDimensions(
graphicsDescriptor.spriteWidth, graphicsDescriptor.spriteHeight,
);
const droid = new WT.Actor(
context, position, dimensions, graphics
);
droid.addEventListener(
WT.EntityEvent.FaceDirection,
() => graphics.direction = droid.direction,
);
return droid;
}
To give the player control of the droid, we just have to add a call to TouchOrClickNav.
window.onload = async (event) => {
const context = await WT.createWorld(worldDescriptor);
const canvas = document.getElementById(worldDescriptor.canvasName);
// Place the droid in the middle(ish) of the map.
const x = 4;
const y = 4;
const droidPosition =
context.grid.getSurfaceLocationAt(x, y).add(new WT.Vector3D(0, 0, 1));
const droid = await createDroid(context, droidPosition);
const camera = new WT.TrackerCamera(
context.scene,
canvas.width,
canvas.height,
droid,
);
// This will setup event listeners on 'mousedown' and 'touchstart' to run the a-star
// pathfinding code and setup the droid to move there, if possible.
WT.TouchOrClickNav(context, canvas, camera, droid, 1);
const update = function() {
if (document.hasFocus()) {
context.update(camera);
}
window.requestAnimationFrame(update);
};
window.requestAnimationFrame(update);
};
The code is running in the canva below (if your screen is big enough).