From ea8e3c2222a9f4a0786e4bd6a9a880a751dfbc3b Mon Sep 17 00:00:00 2001 From: Steven Fawcett Date: Sat, 10 Dec 2022 23:06:40 +0000 Subject: [PATCH] corrected direction --- src/index.mjs | 52 ++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 7 deletions(-) diff --git a/src/index.mjs b/src/index.mjs index 47089a4..c8a5224 100644 --- a/src/index.mjs +++ b/src/index.mjs @@ -1,13 +1,19 @@ import * as Files from "./modules/file.js" import * as Draw from "./modules/draw.js" -var HEADING=0; // DESIRED HEADING +var HEADING = 0; // DESIRED HEADING var _HEADING = 0; // DIAL HEADING -var FPS = 50 ; // SPEED DIAL REFRESHS +var FPS = 25 ; // SPEED DIAL REFRESHS +var DIRECTION = 0; export function SetHeading( hdg ) { - HEADING = 360 - hdg; + HEADING = 360 - mod(hdg , 360); + if( HEADING == 0 ) + { + HEADING = 360 + } + DIRECTION = direction() } export function Compass() { var canvas = document.querySelector("canvas"); @@ -23,14 +29,12 @@ export function Compass() { img.onload = function () { setInterval(function () { - // Need a proper function to drive - if( HEADING != _HEADING ) - _HEADING += 1; + rotate(); ctx.save(); //saves the state of canvas ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas ctx.translate(canvas.width/2, canvas.height/2); //let's translate - ctx.rotate(Math.PI / 180 * (_HEADING )); //increment the angle and rotate the image + ctx.rotate( radians( _HEADING ) ); ctx.translate(-(canvas.width/2), -(canvas.height/2)); //let's translate Draw.drawImageScaled(img , ctx ); ctx.restore(); @@ -39,3 +43,37 @@ export function Compass() { }, FPS); } } + +function rotate() +{ + if( Math.abs( HEADING % 360 )== Math.abs( _HEADING % 360 ) ) return ; + + _HEADING = mod(_HEADING , 360); + + _HEADING += DIRECTION; + + //console.log( "Target Heading = " + _HEADING ); + //console.log( "Requested Heading = " + HEADING); +} + +function direction() +{ + var a = ( _HEADING % 360 ) - HEADING + a = (a + 180) % 360 + + + console.log( "Direction " + a); + + return ( a < 0 ) ? -1 : 1; +} + +function mod( a, n ) +{ + return a - Math.floor( a / n) * n ; + +} + +function radians( degree ) +{ + return degree * Math.PI / 180; +} \ No newline at end of file