inverse kinematics 3 arms
first attempt.
improvements:
the arms are all equal lengths right now
by frogggeee McFrogggeee
HTML
<p id = "text">
</p>
<canvas id = "canvas" width = "480" height = "360" style = "border: 1px solid;"></canvas>
JavaScript
let ctx = document.getElementById("canvas").getContext("2d");
let mx = 0;
let my = 0;
let arm1 = 88;
let arm2 = 88;
let arm3 = 88;
let x = 240;
let y = 360;
let endX;
let endY;
let servo1 = 0;
let servo2 = 0;
let side = 1;
document.addEventListener("mousemove", function moved(e) {
const rect = e.target.getBoundingClientRect();
mx = e.clientX - rect.left;
my = e.clientY - rect.top;
});
function line(x, y, x2, y2, style) {
ctx.strokeStyle = style;
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x2, y2);
ctx.stroke();
endX = x2;
endY = y2;
}
function dir(x, y, x2, y2) {
return toDeg(Math.atan((y - y2) / (x - x2))) + (180 * (x - x2 > 0))
}
function arm(x, y, length, dir, style) {
dir -= 0;
line(x, y, x + Math.cos(toRad(dir)) * length, y + Math.sin(toRad(dir)) * length, style);
}
function toRad(deg) {
return deg * 3.14159 / 180;
}
function toDeg(rad) {
return rad * (180 / 3.14159);
}
function render() {
ctx.clearRect(0, 0, 1000, 1000);
const mouseDir = dir(x, y, mx, my);
const distance = Math.sqrt((x - mx) * (x - mx) + (y - my) * (y - my));
const dist = (distance-arm1)/2;
let A = toDeg(Math.acos(dist/arm1));
if (isNaN(A)) {
A = 0;
}
let B = 90+(180-(90+A));
if (A == 180) {
B = 0;
}
const servo1 = mouseDir - A;
const servo2 = servo1 + (180-B);
const servo3 = servo2 + (180-B);
arm(x, y, arm1, servo1, "red");
arm(endX, endY, arm2, servo2, "blue")
arm(endX, endY, arm3, servo3, "green")
//arm(x, y, distance, mouseDir, "red");
}
setInterval(render, 10);