Steering
Steering algorithm for an RC-Car that translates x and y to left and right
by Alex Oros
HTML
<h1>Steering</h1>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #000000;">
</canvas>
<div class="container">
<div id="xy" class="fixed">x y</div>
<div id="cxcy" class="fixed">cx cy</div>
<div id="lr" class="fixed">left right</div>
</div>
CSS
.container{
display:flex;
}
.fixed{
width: 120px;
}
JavaScript
Number.prototype.map = function (in_min, in_max, out_min, out_max) {
return (this - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var rect = canvas.getBoundingClientRect();
var mdown = false;
canvas.addEventListener("mousedown", inputStart, false);
canvas.addEventListener("mouseup", inputEnd, false);
canvas.addEventListener("mouseout", function(e) {
mdown = false;
}, false);
canvas.addEventListener('mousemove', inputMove, false);
canvas.addEventListener("touchstart", inputStart, false);
canvas.addEventListener("touchend", inputEnd, false);
canvas.addEventListener("touchmove", inputMove, false);
function inputStart() {
mdown = true;
}
function inputEnd() {
mdown = false;
}
function inputMove(e) {
if(mdown) {
var pos = getMousePos(e);
map(pos);
centerPos(pos);
toLeftRight(pos);
printPos(pos);
drawHandle(pos);
}
}
function getMousePos(evt) {
var pos = {
x: evt.clientX - Math.round(rect.left),
y: evt.clientY - Math.round(rect.top)
};
pos.ox = pos.x;
pos.oy = pos.y;
return pos;
}
function centerPos(pos) {
pos.cx = pos.x-127;
pos.cy = pos.y-127;
}
function toLeftRight(pos) {
pos.left = pos.cy+pos.cx;
pos.right = pos.cy-pos.cx;
return pos;
}
function map(pos) {
pos.x = Math.round(pos.x.map(0, rect.width, 0, 254));
pos.y = 254 - Math.round(pos.y.map(0, rect.height, 0, 254));
}
function printPos(pos) {
document.getElementById("xy").innerHTML = "x:"+pos.x + " y:" + pos.y;
document.getElementById("cxcy").innerHTML = "cx:"+pos.cx + " cy:" + pos.cy;
document.getElementById("lr").innerHTML = "l:"+pos.left + " r:" + pos.right;
}
function drawHandle(pos) {
ctx.clearRect(0, 0, rect.width, rect.height);
var s = 10;
ctx.fillRect(pos.ox-s/2, pos.oy-s/2, s, s);
ctx.beginPath();
ctx.moveTo(rect.width/2,...