Enhancing the Mario gaming experience with a bespoke Typescript camera feature

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.

Answer №1

The code Camera.prototype.View.width is incorrect because View is actually a method of the Camera class. To demonstrate, consider the following snippet:

var cam = new Camera();
cam.View(null);

This mistake indicates a possible confusion with classes, instances, and methods. It would be beneficial to learn more about how classes are implemented in TypeScript, which you can find information on here. If you're interested in accessing Camera.View, it's essential to understand static properties as well.

In case your goal was to create a default canvas view with preset dimensions, you could achieve that like so:

var defaultView = new Camera();
defaultView.x = 0; 
defaultView.y = 0;
defaultView.width = canvas.width; 
defaultView.height = canvas.height;

However, attempting to assign a value to Camera.View using Math.floor(...) makes no sense as Camera.View is not defined. Perhaps you meant to adjust the x-coordinate of the view. In such a scenario, considering the existing view variable, you may do:

view.x = Math.floor(mario.position.x + (mario.frameWidth/2) - (view.width / 2));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Divide the elements of the array separated by white space into individual components within the array

Scenario I am in the process of creating a basic webpage that will allow me to showcase and filter bookmarks. Each bookmark can be associated with multiple tags, and tags may be duplicated across different bookmarks. The tags for each bookmark are stored ...

The meaning gets blurred when using 'this' in a prototype method

Alright, so I am working on a node application that utilizes express. In this particular application, there's an express route set up like this: var MyObject = require('./myObject') , myObject = new MyObject(); app.post('/api/w ...

Support for BigInt is not available in TypeScript version 3.5.*

It seems that TypeScript has supported BigInt since version 3.2, and my project is using TypeScript 3.5. Despite not explicitly declaring any variables as BigInt, I recently integrated a package called BufferUtility from https://github.com/Pharuxtan/Buffer ...

The result of the $.post() request is back

In my current code, I am using a jQuery $.post function like this: $.post('/test', json_data, function(data) { result = data }); This function is being used in a validation process where the return value (data) contains either true or false ...

Utilizing nested v-for in Vue.js with lodash's groupBy function

When fetching data from a database, I am using lodash groupby to group my data like so: var vm = this axios.get(this.buildURL()) .then(function(response) { Vue.set(vm.$data, 'model', response.data.model) vm.groupData = _.groupBy(vm.model ...

Creating JavaScript validation conditions based on certain criteria

I am currently working on validating whether a username exists in the database or not. If it does exist, an error message should be displayed, and the user should be prevented from adding details to the database until they edit the username field to make i ...

Can integer values be stored in localStorage similar to JavaScript objects and retrieved without requiring typecasting?

After setting an integer value to a localStorage item: localStorage.setItem('a', 1) and checking its data type: typeof(localStorage.a) "string" it shows as a string. I then typecast it to an int for my purposes: parseInt(localStorage.a) My ...

Expanding an array in JavaScript

I need assistance with... let a = ['a', 2, 3]; a += function(){return 'abc'}; console.log(a[3]); Therefore, I am looking for a shorthand method to push() in array with the above content. Does anyone know of an operator that can help ...

The state update does not seem to be affecting the DOM

I've implemented this component in my React app. It updates the state every second, but oddly enough the value <p>{this.state.time}</p> is not changing as expected. When I print the state value, it does change every second. import React f ...

Leveraging Google Cloud Functions with Next.js (Client-Side Rendering)

Having trouble incorporating firebase cloud functions into my Next.js project, encountering an unfamiliar error. firebase-config.js const firebaseConfig = { apiKey: '~~~', authDomain: '~~', projectId: '~~~', storageBu ...

Tips for simulating http.ServerResponse and http.IncomingMessage when using express.static

Testing my own route handlers has always been straightforward, but I recently encountered an issue while trying to test express's static handler. Despite my best efforts, I can't seem to figure out why it's stalling. There must be a callback ...

Can you include conditional logic within a switch statement?

I've been using if, else if, and else statements in my code but recently switched to switch statements which have made things much simpler. Now I'm wondering if it's possible to add multiple conditions inside a switch statement, similar to i ...

Is there a way to access the initial item in a JavaScript array?

Recently, I've been delving into the world of javascript and encountered a task that involves removing the first item from an array. Solution One function getFirst(arr, item) { arr.push(item); var removed = arr.shift(); return removed; } S ...

Is it possible to globally delay the execution of WebElement.sendKeys() in Protractor's onPrepare function?

While running protractor on a sluggish machine, I am in need of slowing down each key press and action performed. The action part has been successfully implemented, but how can I achieve the same for key presses? I have come up with a local solution which ...

What steps can I take to stop an AJAX request from causing the page to reload

I am facing an issue with my AJAX code where it reloads after a successful upload on the server side. Below is my HTML code that I have included. Any help or suggestions would be greatly appreciated. Thank you. function UploadVid(){ var file = $("#in ...

The database powered by Postgresql performs flawlessly when it comes to updating data with accurate code execution. However, there seems to be an

Imagine a zoo with a postgresql database. To enable web access to this database, I am using php and javascript. Most of the web pages are working fine, but I am currently working on a page where clients can add or remove animals from existing exhibits. T ...

What is the best way to conceal a button before printing and have it reappear once the printing process is finished?

I have a button on my webpage with the id "print_req" that is used to trigger a JavaScript function for printing the page. I want this button to be hidden during the printing process and then reappear afterwards, so it does not show up in the printed docum ...

Making AngularJS 'PUT' requests: The process of submitting only the data in a form

I am facing an issue while updating user data in Angular. When I send a 'PUT' request, the entire user $scope is being sent instead of only the fields visible on the form. To retrieve and update the data, I am using a Factory. Below is my edit f ...

Is it a usual technique to retrieve dynamic content using PhoneGap?

Recently, I've been utilizing phonegap for creating mobile applications on various platforms. I've noticed the need to use AJAX calls within JavaScript to fetch dynamic content. I'm curious, is it a standard practice in HTML5 apps to retrie ...

Switch to TypeScript from JavaScript

Hey, I need assistance translating this code into TypeScript. Can you lend a hand? import mongoose, { Promise } from 'mongoose'; Promise = global.Promise; const db = {}; db.mongoose = mongoose; db.user = require("./user.model"); db.r ...