diff --git a/script.js b/script.js index 35be137..650568d 100644 --- a/script.js +++ b/script.js @@ -45,6 +45,10 @@ class SwerveModule { // Swerve drive class to represent the robot as a whole class SwerveDrive { constructor(modulePositionsAndNames) { + this.setModules(modulePositionsAndNames); + } + + setModules(modulePositionsAndNames) { // Take an array of module positions with a name and create an array of SwerveModule objects this.modules = modulePositionsAndNames.map(module => new SwerveModule(module.x, module.y, module.name) @@ -62,7 +66,10 @@ class SwerveDrive { if (maxCalculated > maxSpeed) { const scale = maxSpeed / maxCalculated; this.modules.forEach(module => { - module.speed *= scale; + module.velocity.x *= scale; + module.velocity.y *= scale; + module.speed = module.velocity.magnitude(); + module.angle = module.velocity.angle(); }); } } @@ -225,7 +232,7 @@ function drawGrid(ctx, sideLength, gridSquareSize, xOffset, yOffset, rotation) { function drawModule(ctx, module) { const x = module.position.x; const y = module.position.y; - const arrowLength = Math.max(module.speed * 1.5, 5); + const arrowLength = Math.max(module.speed / 2, 5); ctx.save(); ctx.translate(x, y); @@ -300,22 +307,25 @@ function animate() { ctx.save(); ctx.translate(canvas.width / 2, canvas.height / 2); - // Animation for testing - xSpeed = vxSlider.value; - ySpeed = vySlider.value; - turnSpeed = omegaSlider.value; + // Update speeds based on sliders + xSpeed = parseFloat(vxSlider.value); + ySpeed = parseFloat(vySlider.value); + turnSpeed = parseFloat(omegaSlider.value); // Animate the grid with robot movement let offsetSpeedDivisor = (100 - gridSquareSize <= 0 ? 1 : 100 - gridSquareSize); - console.log(offsetSpeedDivisor); - - // Accumulate grid offset and wrap it to create infinite grid effect - xGridOffset = (xGridOffset + (xSpeed / offsetSpeedDivisor)) % gridSquareSize; - yGridOffset = (yGridOffset + (ySpeed / offsetSpeedDivisor)) % gridSquareSize; - - // Accumulate robot rotation based on turn speed (convert to radians) robotRotation += turnSpeed * 0.01; // Scale factor for reasonable rotation speed + // Convert robot velocities to world velocities for grid movement + const cosRot = Math.cos(robotRotation); + const sinRot = Math.sin(robotRotation); + const worldVx = xSpeed * cosRot - ySpeed * sinRot; + const worldVy = xSpeed * sinRot + ySpeed * cosRot; + + // Update grid offsets based on robot movement + xGridOffset = (xGridOffset + (worldVx / offsetSpeedDivisor)) % gridSquareSize; + yGridOffset = (yGridOffset + (worldVy / offsetSpeedDivisor)) % gridSquareSize; + // Draw the robot and it's movement. Grid should be oversized so movement // doesn't find the edge of the grid drawGrid(ctx, canvas.width * 2, gridSquareSize, xGridOffset, yGridOffset, robotRotation);