I have my HTML5 document that contains JavaScript code. The script defines a constructor to create a car object along with methods to compute the position of the car as the mouse moves and draw it in canvas.
I'm not getting any errors in the Chrome browser console and the log messages aren't showing any problems, but the car isn't showing. here's the code:
Edit: In this game, the car rotates and moves following the the mouse position. Also, I have a viewport that must centered around the car. So before drawing anything, I translate the origin of the canvas to (camx, camy), which according to my calculations are where the canvas should be positioned for it to be centered around the car.
Basically, my idea is: Instead of scrolling the viewport around the map, the viewport remains stationary and I just move the entire canvas.
function Car(x, y, orientation, id, type) {
// x and y are the cooredinates of the center of a car object
this.x = x;
this.y = y;
this.type = type;
this.speed = 5; // default speed = 5
this.isAlive = 1;
this.stillExists = 1;
this.id = id;
this.orientation = orientation;
this.img = new Image();
this.img.source = "car1.png";
this.img.width = 200;
this.img.x = this.x;
this.img.y = this.y;
this.img.height = 100;
this.img.orientation = this.orientation;
// update position and orienttaion of car based on mouse position
this.updatePosAndOrien = function() {
// caclcuate orientation using mousex and mousey and x y position of our car
var targetX = mousex - this.x;
var targetY = mousey - this.y;
var trgtOrien = Math.atan2(targetY, targetX);
this.orientation = trgtOrien;
//calculate position
var dx = mousex -this.x ;
var dy = mousey - this.y ;
var distance = Math.sqrt(dx*dx + dy*dy);
var factor = distance / this.speed;
var xspeed = dx / factor;
var yspeed = dy / factor;
this.x = this.x + xspeed;
this.y = this.y+ yspeed;
};
// draw method that draws the car on canvas
this.draw = function() {
this.img.onload = function() {
ctx.save(); // save context
ctx.translate(Math.round(this.x), Math.round(this.y)); // translate or move context origin to center of image
ctx.rotate(this.orientation);
ctx.drawImage(img, -(this.width / 2), -(this.height / 2),
this.width, this.height);
ctx.restore(); // restore context
}
};
}
function drawIt() {
if (ourCar != undefined) {
ourCar.updatePosAndOrien();
console.log("drawing the car");
ourCar.draw();
}
console.log("car is not defined");
requestAnimationFrame(drawIt);
}
// player
var ourCar = new Car(300, 400, 2, 111, 1);
requestAnimationFrame(drawIt);
body {
overflow: hidden;
}
<canvas onmousemove=" load(event)" id="myCanvas" width="5000" height="5000"></canvas>