The Good Guy
The Good Guy

Reputation: 31

Duplicating function after delay

I have a function which allows my car to go from top to bottom and now i want this car to repeat itself when it reaches the end of the canvas. So when my car goes to the bottom, it should reappear at the top again and keep doing that.

This is my function that draws the car:

//=====================
//ENTER: OBSTACLE CAR
//=====================

//Uploading car
var car1 = new Image();
car1.src = "img/Car.png";

//Setting properties of car
var x1 = 450;
var y1 = 40;
var speed1 = 0.1;
var angle1 = 180;
var mod1 = 0;

//Interval for animation
 var moveInterval = setInterval(function () {
     drawCar();
 }, 300);

//Drawing the car turning and changing speed
function drawCar() {


          x1 += (speed1 * mod1) * Math.cos(Math.PI / 180 * angle1);
          y1 += (speed1 * mod1) * Math.sin(Math.PI / 180 * angle1);

          context.save();
          context.translate(x1, y1);
          context.rotate(Math.PI / 180 * angle1);
          context.drawImage(car1, -(car1.width / 1), -(car1.height / 1));
          context.restore();

          }

This is my return function with setInterval, which doesn't work:

setInterval(function(drawCar) {

      x1 += (speed1 * mod1) * Math.cos(Math.PI / 180 * angle1);
      y1 += (speed1 * mod1) * Math.sin(Math.PI / 180 * angle1);

context.save();
context.translate(x1, y1);
context.rotate(Math.PI / 180 * angle1);
context.drawImage(car1, -(car1.width / 1), -(car1.height / 1));
context.restore();    

 }, 1000); // every 1000 ms

Upvotes: 0

Views: 22

Answers (1)

user1693593
user1693593

Reputation:

You need to reset your counters when they reach a certain limit, ie. the edge of the canvas, f.ex. inside your drawCar() method:

if (x1 > context.canvas.width ) x1 = -car1.width;
if (y1 > context.canvas.height) y1 = -car1.height;

Adjust as needed depending on what you're after.

(Also remember to use an onload handler with image loading).

Upvotes: 1

Related Questions