
previous

page 7
next
We can now write a step forward function (fd()) and a right turn function (rt()).
function fd() {
g_ctx.beginPath();
g_ctx.moveTo(g_x,g_y);
var dx=0; var dy=0;
if (g_h==0) dy=-g_step;
if (g_h==90) dx=g_step;
if (g_h==180) dy=g_step;
if (g_h==270) dx=-g_step;
g_x=g_x+dx; g_y=g_y+dy;
g_ctx.lineTo(g_x,g_y);
g_ctx.stroke();
}
function rt() {
g_h=g_h+90;
if (g_h==360) g_h=0;
}
g_ctx.beginPath();
g_ctx.moveTo(g_x,g_y);
var dx=0; var dy=0;
if (g_h==0) dy=-g_step;
if (g_h==90) dx=g_step;
if (g_h==180) dy=g_step;
if (g_h==270) dx=-g_step;
g_x=g_x+dx; g_y=g_y+dy;
g_ctx.lineTo(g_x,g_y);
g_ctx.stroke();
}
function rt() {
g_h=g_h+90;
if (g_h==360) g_h=0;
}
To test my new functions, I temporarily changed index.html like this:
<script>setup(); fd(); rt(); fd();</script>

previous
next