Bresenham AI
by Sam Fereday
HTML
<div id="container"></div>
CSS
body {
font: 85%/1.4em arial;
}
#output {
position: relative;
padding: 1em;
}
.node {
width: 52px;
height: 52px;
padding: 6px;
text-align: center;
box-sizing: border-box;
background: #333;
position: absolute;
display: block;
color: #fff;
}
.mover {
width:52px;
height:52px;
position: absolute;
background: #990000;
transition: all 0.2s ease;
z-index: 999;
}
JavaScript
// Still to do:
// - Able to head back the opposite direction
// - Flip the x and y because currently they don't make sense on screen
// - Add the ability to easily chain a new path after the previous one
var container = document.getElementById("container");
// Only one problem, top is actually along the x axis here, so it needs flipping.
var Coordinate = function(x, y, dx, dy, ep){
this.x = x || -1;
this.y = y || -1;
this.dx = dx || -1;
this.dy = dy || -1;
this.endPoint = ep;
}
// Your origin (of the entity) - hard coded for example
originX = 1;
originY = 1;
// Path grouping
var currentPathGroupIndex = 0;
// Bresenham straight line algorithm (better sort)
// http://stackoverflow.com/questions/4672279/bresenham-algorithm-in-javascript
function calcStraightLine (startCoordinates, endCoordinates, ep) {
var coordinatesArray = new Array();
// Translate coordinates
var x1 = startCoordinates.left;
var y1 = startCoordinates.top;
var x2 = endCoordinates.left;
var y2 = endCoordinates.top;
// Define differences and error check
var dx = Math.abs(x2 - x1);
var dy = Math.abs(y2 - y1);
var sx = (x1 < x2) ? 1 : -1;
var sy = (y1 < y2) ? 1 : -1;
var err = dx - dy;
// Set first coordinates
coordinatesArray.push(new Coordinate(y1, x1, y2, x2, ep));
// Main loop (don't like whiles, will change this)
while (!((x1 == x2) && (y1 == y2))) {
var e2 = err << 1;
if (e2 > -dy) {
err -= dy;
x1 += sx;
}
if (e2 < dx) {
err += dx;
y1 += sy;
}
// Set coordinates (this may be where to flip them)
coordinatesArray.push(new Coordinate(y1, x1, y2, x2, ep));
}
// Return the result
return coordinatesArray;
}
// A cache to store our current coords. These would be purged upon new path calculation
var coords = [];
// Couple of coord sets (notice the end of the first set toward the next, we could automate this...