I am working on creating an educational Mario game without the use of PhaserJS or any other engine.
Currently, I am faced with the challenge of implementing a camera that can follow Mario as he moves.
As it stands, Mario can walk off the screen in one direction. I need assistance incorporating a camera that tracks Mario's movements.
Here is how my canvas looks:
var w = 720, h = 480;
var canvas: HTMLCanvasElement;
var ctx: CanvasRenderingContext2D;
var downForce = 2;
HTML:
<canvas id="canvas" width="720" height="480" style="border:1px solid #c3c3c3;"></canvas>
My current GameLoop function looks like this:
function gameLoop() {
requestAnimationFrame(gameLoop);
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = "rgb(174,238,238)";
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = "rgb(14,253,1)";
var floor = ctx.fillRect(0, h - 45, w, 45);
mario.drawSprite();
pipe.drawSprite();
mario.addGravity();
}
I have created a Camera.ts file:
class Camera {
x: number;
y: number;
width: number;
height: number;
constructor(){}
View(input: any):any {
this.x = 0;
this.y = 0;
this.width = canvas.width;
this.height = canvas.height;
}
}
The goal is to have the camera move along with Mario. The keyboardInput function attempts to achieve this:
function keyboardInput(event: KeyboardEvent) {
switch (event.keyCode) {
case 65: case 37: //a
mario.setSpriteUrl("graphics/mario/small/Running-mario-left.gif");
mario.numberOfFrames = 4;
mario.position.x -= 10;
Camera.View = Math.floor(mario.position.x + (mario.frameWidth/2) - (Camera.prototype.View.width / 2))
break;
I am having trouble with the calculation for moving the camera and Visual Studio indicates that the 'view' property does not exist.
I am struggling to implement the camera feature and would greatly appreciate any help in resolving this issue. It seems like modifying the gameloop may be necessary to get the camera functioning correctly.