I am making a game in JS where a player has to move in a grid movement and the grid contains squares of different colours. Each colour should affect the player's speed. I am learning JS so I appreciate any help.

I have the following code at the moment:


<!DOCTYPE html>
        <title>The Grid Game</title>
        <canvas id="canvas"></canvas>
        <script type="text/javascript" src="game.js"></script>

and game.js:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

canvas.width = 800;
canvas.height = 600;

 // Create the sprite (a square lol)
var mySprite = {
    x: 200,
    y: 200,
    width: 50,
    height: 50,
    speed: 200,
    color: '#c00'

var keysDown = {};
window.addEventListener('keydown', function(e) {
    keysDown[e.keyCode] = true;
window.addEventListener('keyup', function(e) {
    delete keysDown[e.keyCode];

function update(mod) {
    if (37 in keysDown) {
        mySprite.x -= mySprite.speed * mod;
    if (38 in keysDown) {
        mySprite.y -= mySprite.speed * mod;
    if (39 in keysDown) {
        mySprite.x += mySprite.speed * mod;
    if (40 in keysDown) {
        mySprite.y += mySprite.speed * mod;

function render() {
    ctx.fillStyle = '#000';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = mySprite.color;
    ctx.fillRect(mySprite.x, mySprite.y, mySprite.width, mySprite.height);

function run() {
    update((Date.now() - time) / 1000);
    time = Date.now();

var time = Date.now();
setInterval(run, 10);

How can I change this to a grid with different colour squares that affect the player's speed?

Thanks in advance...

Edited by Kent55

4 Years
Discussion Span
Last Post by Dervish1

Since you're doing all the rendering work in your canvas, why not simply draw the squares you want on the canvas and change the rendering speed when the user moves over them?

As someone else suggested, search for 'collision detection' and write your own code to implement it. Trying to get the browser to do that work for you would require not using the canvas at all, I would think.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.