-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.js
83 lines (69 loc) · 2.31 KB
/
script.js
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Setting things up
const OFFSET = 200;
$ = document.querySelector.bind(document);
function ik_2d(x, y, d1, d2) {
let dist = Math.sqrt(x ** 2 + y ** 2);
let theta1 = Math.atan2(y, x) - Math.acos((dist ** 2 + d1 ** 2 - d2 ** 2) / (2 * d1 * dist));
let theta2 = Math.atan2(y - d1 * Math.sin(theta1), x - d1 * Math.cos(theta1));
return {theta1, theta2};
}
// Drawing
function render(angles, d1, d2) {
let seg1 = $('#segment1');
let seg2 = $('#segment2');
let end = $('#end-effector');
if (isNaN(angles.theta1) || isNaN(angles.theta2))
return
let elbowX = Math.cos(angles.theta1) * d1 + OFFSET;
let elbowY = Math.sin(angles.theta1) * d1 + OFFSET;
let wristX = elbowX + Math.cos(angles.theta2) * d2
let wristY = elbowY + Math.sin(angles.theta2) * d2;
seg1.setAttribute('x1', OFFSET);
seg1.setAttribute('y1', OFFSET);
seg1.setAttribute('x2', elbowX);
seg1.setAttribute('y2', elbowY);
seg2.setAttribute('x1', elbowX);
seg2.setAttribute('y1', elbowY);
seg2.setAttribute('x2', wristX);
seg2.setAttribute('y2', wristY);
end.setAttribute('cx', wristX);
end.setAttribute('cy', wristY);
}
// Click and drag stuff
function selectEndEffector(event) {
let svg = $('svg');
svg.addEventListener("mousemove", moveEndEffector);
svg.addEventListener("mouseup", deselectEndEffector);
svg.addEventListener("mouseleave", deselectEndEffector);
dragStartX = event.clientX;
dragStartY = event.clientY;
console.log("box", dragStartX, dragStartY);
}
function deselectEndEffector(event) {
let svg = $('svg');
svg.removeEventListener("mousemove", moveEndEffector);
svg.removeEventListener("mouseup", deselectEndEffector);
svg.removeEventListener("mouseleave", deselectEndEffector);
x += event.clientX - dragStartX;
y += event.clientY - dragStartY;
}
function moveEndEffector(event) {
x += event.clientX - dragStartX;
y += event.clientY - dragStartY;
dragStartX = event.clientX;
dragStartY = event.clientY;
}
///// MAIN STUFF
var x = 100, y = 200;
function update() {
let d1 = $('input#slider1').value;
let d2 = $('input#slider2').value;
$('span#label1').textContent = d1;
$('span#label2').textContent = d2;
let angles = ik_2d(x, y, d1, d2);
render(angles, d1, d2);
}
window.onload = () => {
$('#end-effector').addEventListener("mousedown", selectEndEffector);
setInterval(update, 1/10);
}