3 Commits

3 changed files with 214 additions and 12 deletions

View File

@ -199,7 +199,7 @@ if scale < 1:
<legend>Translation &amp; Rotation</legend>
<div class="control-group">
<button id="control-mode-toggle" type="button">Switch to Keyboard Controls (WASD + QE)</button>
<button id="control-mode-toggle" type="button">Switch to Keyboard/Joystick Controls</button>
</div>
<div id="slider-controls">

218
script.js
View File

@ -4,6 +4,81 @@
import GrahamScan from "./vendor/lucio/graham-scan.mjs";
class Joystick {
constructor(ctx, x, y, radius) {
this.ctx = ctx;
this.x = x;
this.y = y;
this.radius = radius;
this.nubX = x;
this.nubY = y;
this.active = false;
this.visible = false;
}
draw() {
if (!this.visible)
return;
this.ctx.save();
this.ctx.beginPath();
this.ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
this.ctx.fillStyle = rootStyles.getPropertyValue('--primary-dark-blue');
this.ctx.fill();
this.ctx.beginPath();
this.ctx.arc(this.nubX, this.nubY, this.radius / 3, 0, Math.PI * 2);
this.ctx.fillStyle = rootStyles.getPropertyValue('--accent-blue');
this.ctx.fill();
this.ctx.restore();
}
checkShouldActivate(x, y) {
if (!this.touchInRange(x, y))
return;
this.active = true;
this.processTouch(x, y);
}
deactivate() {
this.active = false;
}
touchInRange(x, y) {
const deltaX = x - this.x;
const deltaY = y - this.y;
const dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
return dist <= this.radius;
}
processTouch(x, y) {
if (this.touchInRange(x, y) && this.active) {
this.nubX = x;
this.nubY = y;
}
}
reset() {
this.nubX = this.x;
this.nubY = this.y;
}
getX() {
return (this.nubX - this.x) / this.radius;
}
getY() {
return (this.y - this.nubY) / this.radius;
}
setIsVisible(visible) {
this.visible = visible;
}
}
// 2D vector class to make some of the math easier
class Vec2D {
constructor(x, y) {
@ -269,6 +344,15 @@ const PresetConfigs = {
* BEGIN DOM VARIABLES
*/
// Get canvas
const canvas = document.getElementById('swerve-canvas');
// Get the canvas context as constant
const ctx = canvas.getContext('2d');
// Get CSS variables for use in canvas
const rootStyles = getComputedStyle(document.documentElement);
// Get all control elements
const vxSlider = document.getElementById('vx-slider');
const vySlider = document.getElementById('vy-slider');
@ -379,17 +463,21 @@ controlModeToggle.addEventListener('click', () => {
vxOutput.textContent = '0';
vyOutput.textContent = '0';
omegaOutput.textContent = '0';
leftJoystick.setIsVisible(true);
rightJoystick.setIsVisible(true);
} else {
// Switch to slider mode
sliderControls.style.display = 'block';
keyboardControls.style.display = 'none';
controlModeToggle.textContent = 'Switch to Keyboard Controls (WASD + QE)';
controlModeToggle.textContent = 'Switch to Keyboard/Joystick Controls';
// Reset manual input state
Object.keys(keyState).forEach(key => keyState[key] = false);
manualInputVelX = 0;
manualInputVelY = 0;
manualInputOmega = 0;
leftJoystick.setIsVisible(false);
rightJoystick.setIsVisible(false);
}
});
@ -552,6 +640,105 @@ applyCustomBtn.addEventListener('click', () => {
updateModuleDisplays(robot);
});
function convertTouchToCanvas(inCoords) {
const rect = canvas.getBoundingClientRect();
// Calculate the scale factor between display size and canvas internal size
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
// Convert client coordinates to canvas coordinates, accounting for scaling
const x = (inCoords.x - rect.left) * scaleX - canvas.width / 2;
const y = (inCoords.y - rect.top) * scaleY - canvas.height / 2;
return { x, y };
}
canvas.addEventListener('mousedown', (event) => {
const canvasCoords = convertTouchToCanvas({ x: event.clientX, y: event.clientY });
leftJoystick.checkShouldActivate(canvasCoords.x, canvasCoords.y);
rightJoystick.checkShouldActivate(canvasCoords.x, canvasCoords.y);
});
canvas.addEventListener('mousemove', (event) => {
const canvasCoords = convertTouchToCanvas({ x: event.clientX, y: event.clientY });
leftJoystick.processTouch(canvasCoords.x, canvasCoords.y);
rightJoystick.processTouch(canvasCoords.x, canvasCoords.y);
});
canvas.addEventListener('mouseup', (event) => {
leftJoystick.deactivate();
rightJoystick.deactivate();
});
// Touch event listeners for mobile/tablet support
canvas.addEventListener('touchstart', (event) => {
event.preventDefault(); // Prevent scrolling and default touch behavior
for (let i = 0; i < event.touches.length; i++) {
const touch = event.touches[i];
const canvasCoords = convertTouchToCanvas({ x: touch.clientX, y: touch.clientY });
// alert(`X: ${canvasCoords.x}, Y: ${canvasCoords.y}`);
leftJoystick.checkShouldActivate(canvasCoords.x, canvasCoords.y);
rightJoystick.checkShouldActivate(canvasCoords.x, canvasCoords.y);
}
});
canvas.addEventListener('touchmove', (event) => {
event.preventDefault(); // Prevent scrolling while using joysticks
for (let i = 0; i < event.touches.length; i++) {
const touch = event.touches[i];
const canvasCoords = convertTouchToCanvas({ x: touch.clientX, y: touch.clientY });
leftJoystick.processTouch(canvasCoords.x, canvasCoords.y);
rightJoystick.processTouch(canvasCoords.x, canvasCoords.y);
}
});
canvas.addEventListener('touchend', (event) => {
event.preventDefault();
// If no touches remain, deactivate both joysticks
if (event.touches.length === 0) {
leftJoystick.deactivate();
rightJoystick.deactivate();
} else {
// Check if the remaining touches are still in range of the joysticks
let leftStillActive = false;
let rightStillActive = false;
for (let i = 0; i < event.touches.length; i++) {
const touch = event.touches[i];
const canvasCoords = convertTouchToCanvas({ x: touch.clientX, y: touch.clientY });
if (leftJoystick.touchInRange(canvasCoords.x, canvasCoords.y)) {
leftStillActive = true;
}
if (rightJoystick.touchInRange(canvasCoords.x, canvasCoords.y)) {
rightStillActive = true;
}
}
if (!leftStillActive) {
leftJoystick.deactivate();
leftJoystick.reset();
}
if (!rightStillActive) {
rightJoystick.deactivate();
rightJoystick.reset();
}
}
});
canvas.addEventListener('touchcancel', (event) => {
// Handle touch cancellation (e.g., when system interrupts)
leftJoystick.deactivate();
leftJoystick.reset();
rightJoystick.deactivate();
rightJoystick.reset();
});
/*
* END LISTENER CODE
* BEGIN DYNAMIC DOM FUNCTIONS
@ -696,12 +883,8 @@ function updateModuleDisplays(robot) {
* BEGIN ANIMATION CODE
*/
// Get the canvas and context as constants
const canvas = document.getElementById('swerve-canvas');
const ctx = canvas.getContext('2d');
// Get CSS variables for use in canvas
const rootStyles = getComputedStyle(document.documentElement);
const leftJoystick = new Joystick(ctx, -250, 250, 100);
const rightJoystick = new Joystick(ctx, 250, 250, 100);
function drawGrid(ctx, sideLength, gridSquareSize, xOffset, yOffset) {
ctx.save();
@ -806,8 +989,12 @@ function drawRobot(ctx, robot, heading) {
ctx.restore(); // Restore to remove rotation
}
// Initialize Variables
// Joysticks
const supportsTouch = (navigator.maxTouchPoints > 0);
// General robot
const robotSize = 200;
const defaultModulePositions = PresetConfigs.fourWheelSquare(robotSize);
const robot = new SwerveDrive(defaultModulePositions, "4-Wheel Square");
@ -829,9 +1016,15 @@ function animate() {
// Update speeds based on control mode
if (isManualInputMode) {
xSpeed = manualInputVelX;
ySpeed = -manualInputVelY; // Negative because canvas Y axis is inverted
turnSpeed = manualInputOmega;
const maxSpeed = parseFloat(keyboardMaxSpeed.value);
const maxRotation = parseFloat(keyboardMaxRotation.value);
// xSpeed = manualInputVelX;
// ySpeed = -manualInputVelY; // Negative because canvas Y axis is inverted
// turnSpeed = manualInputOmega;
xSpeed = leftJoystick.getX() * maxSpeed;
ySpeed = -leftJoystick.getY() * maxSpeed;
turnSpeed = rightJoystick.getX() * maxRotation;
} else {
xSpeed = parseFloat(vxSlider.value);
ySpeed = -parseFloat(vySlider.value);
@ -870,6 +1063,9 @@ function animate() {
drawGrid(ctx, canvas.width * 2, gridSquareSize, xGridOffset, yGridOffset);
drawRobot(ctx, robot, robot.gyroHeading);
leftJoystick.draw();
rightJoystick.draw();
// Do it all over again
ctx.restore();
requestAnimationFrame(animate);

View File

@ -361,4 +361,10 @@ button:hover {
.readout .value {
color: var(--text-light);
font-weight: bold;
}
@media only screen and (max-width: 768px) {
main {
display: block;
}
}