2D smooth movement from scratch (javascript, pixelart)

My interest in game development led me to the idea of implementing the logic from scratch, without an engine.

Finally, I came to the point of optimizing the movement sequences of the background in an RPG 2D game. Basically, the implementation was not particularly complex due to the numerous help functions, but I am not completely satisfied.

I’ve only worked with canvas to a limited extent so far, which is why the code I’ve provided here can certainly be optimized. What interests me, however, is how the 8-direction system can be optimized.

Ultimately, it is not the user who is moved, but the background. This results in massive jerks due to the speed of movement and the specified number of pixels that have to be overcome.

Basically, I have a logic that allows me to normalize vectors, but the optimization guides I have noticed are not very helpful.

To make it clearer, I minimized the movement speed. I already played around with some delta values or tried to round some values but this ended very badly in some blurry pixel art.

Any idea in how to optimize this demo?

const game = document.querySelector('#game');
const context = game.getContext('2d');

const background = new Image();
background.src = 'https://i.imgur.com/82hX6qh.png';

const player = new Image();
player.src = 'https://i.imgur.com/LrL69By.png';

const backgroundHeight = 480;
const backgroundWidth = 840;
const playerHeight = 16;
const playerWidth = 12;

const initialGameWidth = 240;
const initialGameHeight = playerWidth * 10;

const cameraSpeed = 0.1;
const step = 1 / 60;

let x = backgroundWidth / 2; // Player Starting X
let y = backgroundHeight / 2; // Player Starting Y
let speed = 1;
let keymap = [];
let previousMs;
let cameraX = x;
let cameraY = y;

game.width = initialGameWidth;
game.height = initialGameHeight;

const handleScreens = () => {
    const scale = window.innerHeight / initialGameHeight;
    game.style.scale = scale;

    const gameHeight = Math.round(window.innerHeight / scale);
    const gameWidth = Math.round(window.innerWidth / scale);

    game.height = gameHeight % 2 ? gameHeight + 1 : gameHeight;
    game.width = gameWidth % 2 ? gameWidth + 1 : gameWidth;
};

handleScreens();
window.addEventListener('resize', () => handleScreens());

window.addEventListener('keydown', event => {
    let index = keymap.indexOf(event.key);

    if (index > -1) {
        keymap.splice(index, 1);
    }

    keymap.push(event.key);
});

window.addEventListener('keyup', event => {
    let index = keymap.indexOf(event.key);

    if (index > -1) {
        keymap.splice(index, 1);
    }
});

const handleCamera = (currentValue, destinationValue) => {
    return currentValue * (1 - cameraSpeed) + destinationValue * cameraSpeed;
};

const handleWork = () => {
    let tempChange = { x: 0, y: 0 };

    [...keymap].forEach(direction => {
        switch (direction) {
            case 'ArrowRight':
                tempChange.x = 1;
                break;
            case 'ArrowLeft':
                tempChange.x = -1;
                break;
            case 'ArrowUp':
                tempChange.y = -1;
                break;
            case 'ArrowDown':
                tempChange.y = 1;
                break;
        }
    });

    let angle = Math.atan2(tempChange.y, tempChange.x);

    if (tempChange.x !== 0) {
        x += Math.cos(angle) * speed;
    }

    if (tempChange.y !== 0) {
        y += Math.sin(angle) * speed;
    }

    cameraX = handleCamera(cameraX, x);
    cameraY = handleCamera(cameraY, y);

    //context.imageSmoothingEnabled = false;
    context.clearRect(0, 0, game.width, game.height);
    context.save();
    context.translate(-cameraX + (game.width / 2) - (playerWidth / 2), -cameraY + (game.height / 2) - (playerHeight / 2));
    context.drawImage(background, 0, 0, backgroundWidth, backgroundHeight);
    context.drawImage(player, 0, 0, playerWidth, playerHeight, x, y, playerWidth, playerHeight);
    context.restore();
};

const main = (timestampMs) => {
    if (previousMs == undefined) {
        previousMs = timestampMs;
    }

    let delta = (timestampMs - previousMs) / 1000;

    while (delta >= step) {
        handleWork();
        delta -= step;
    }

    previousMs = timestampMs - delta * 1000;

    requestAnimationFrame(main);
};

requestAnimationFrame(main);
* {
  margin: 0;
  padding: 0;
}

body {
  background-color: #222;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  height: 100vh;
  width: 100vw;
}

#game {
  -ms-interpolation-mode: nearest-neighbor;
      image-rendering: -moz-crisp-edges;
      image-rendering: pixelated;
}
<canvas id="game"></canvas>

2

If the speed is 7, the map will be displaced 7 pixels at a time, which can look a bit stuttery at a framerate of 24FPS. So the first thing you can do is set the FPS to 60 and the speed a bit lower.

const step = 1 / 60; 
const speed = 3;

It still stutters a bit, but this can also be caused by the browser/cpu doing other things which delays the requestAnimationframe calls.

You might also want to look at translate to move the map around. You can translate the whole canvas except the player character.

ctx.save();
ctx.translate(...); // movement
// draw the map here
ctx.restore();
// draw the player here

const game = document.querySelector('#game');
const context = game.getContext('2d');

const background = new Image();
background.src = 'https://i.imgur.com/Kjrpd2v.png';

const player = new Image();
player.src = 'https://i.imgur.com/PIT6zqs.png';

const initialGameWidth = 640;
const initialGameHeight = 360;

const step = 1 / 60;

let x = 3360 / 2;
let y = 1920 / 2;
let speed = 3;
let keymap = [];
let previousMs;

game.width = initialGameWidth;
game.height = initialGameHeight;

const handleScreens = () => {
    let scale = window.innerHeight / initialGameHeight;
    game.style.scale = scale < 1 ? 1 : scale;

    console.log(game.style.scale)

    game.height = window.innerHeight % 2 ? window.innerHeight - 1 : window.innerHeight;
    game.width = window.innerWidth % 2 ? window.innerWidth - 1 : window.innerWidth;
};

window.addEventListener('resize', () => handleScreens());
handleScreens();

window.addEventListener('keydown', event => {
    let index = keymap.indexOf(event.key);

    if (index > -1) {
        keymap.splice(index, 1);
    }

    keymap.push(event.key);
});

window.addEventListener('keyup', event => {

    let index = keymap.indexOf(event.key);

    if (index > -1) {
        keymap.splice(index, 1);
    }
});

const handleWork = (delta) => {
    let tempChange = { x: 0, y: 0 };

    [...keymap].forEach(direction => {
        switch (direction) {
            case 'ArrowRight':
                tempChange.x = 1;
                break;
            case 'ArrowLeft':
                tempChange.x = -1;
                break;
            case 'ArrowUp':
                tempChange.y = -1;
                break;
            case 'ArrowDown':
                tempChange.y = 1;
                break;
        }
    });

    let angle = Math.atan2(tempChange.y, tempChange.x);

    if (tempChange.x !== 0) {
        x += Math.cos(angle) * speed;
    }

    if (tempChange.y !== 0) {
        y += Math.sin(angle) * speed;
    }

    // const mapX = Math.floor((game.width / 2) - 24 - x) + delta;
    // const mapY = Math.floor((game.height / 2) - 32 - y) + delta;

    const mapX = (game.width / 2) - 24 - x;
    const mapY = (game.height / 2) - 32 - y;

    context.clearRect(0, 0, game.width, game.height);
    context.drawImage(background, 0, 0, 3360, 1920, mapX, mapY, 3360, 1920);
    context.drawImage(player, 0, 0, 48, 64, (game.width / 2) - 24, (game.height / 2) - 32, 48, 64);
};

const main = (timestampMs) => {
    if (previousMs == undefined) {
        previousMs = timestampMs;
    }

    let delta = (timestampMs - previousMs) / 1000;

    while (delta >= step) {
        handleWork(delta);
        delta -= step;
    }

    previousMs = timestampMs - delta * 1000;

    requestAnimationFrame(main);
};

requestAnimationFrame(main);
* {
  margin: 0;
  padding: 0;
}

body {
  background-color: #222;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  height: 100vh;
  width: 100vw;
}

#game {
  -ms-interpolation-mode: nearest-neighbor;
      image-rendering: -moz-crisp-edges;
      image-rendering: pixelated;
}
 <canvas id="game"></canvas>

1

The canvas can only interpret integers, which is why it interpolates with decimal numbers. This interpolation ensures that the pixels are blurred, as an attempt is made to display an intermediate status of the two pixels.

One of the reasons for this is the scaling by CSS, which only scales up the element. The original pixels are still there, they are just perceived as larger.

However, as soon as you start scaling directly via canvas, not only are the pixels perceived as larger, but the interpolation is also improved, as it now has access to the intermediate pixels. This allows intermediate states to be displayed clearly.

This can be implemented as follows via canvas:

context.imageSmoothingEnabled = false;
const scale = window.innerHeight / initialGameHeight;
context.scale(scale, scale);

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật