새소식

Frontend/JavaScript

[JavaScript] keyboard 이벤트로 요소 움직이기

  • -

 

 

keyboard event

 

  • KeyboardEvent.key

The KeyboardEvent interface's key read-only property returns the value of the key pressed by the user, taking into consideration the state of modifier keys such as Shift as well as the keyboard locale and layout.

 

  • KeyboardEvent.code

The KeyboardEvent.code property represents a physical key on the keyboard (as opposed to the character generated by pressing the key). In other words, this property returns a value that isn't altered by keyboard layout or the state of the modifier keys.

 

KeyboardEvent: key=' ' | code='Space’
KeyboardEvent: key='a' | code='KeyA'
KeyboardEvent: key='b' | code='KeyB'
KeyboardEvent: key='c' | code='KeyC'
KeyboardEvent: key='d' | code='KeyD'
KeyboardEvent: key='e' | code='KeyE'
KeyboardEvent: key='f' | code='KeyF'
KeyboardEvent: key='g' | code='KeyG'

 

- e.key: 읽기 전용 속성 제공

- e.code: 키보드의 '키' 자체를 제공

 

 

 

키보드 이벤트는 위와 같다.

화살표 키 네 개인 ArrowLeft, ArrowRight, ArrowUp, ArrowDown의 key, code의 값은 모두 동일함

이번에 화살표키로 캐릭터를 움직이는 기능을 개발하는 데는 code 값을 이용했다.

 

 

 

if (leftPressed && hero.x > 0) {
    hero.x -= speed;
  }

상하좌우로 이동은 하는데 캔버스 영역 밖으로 hero(파란 사각형)가 나가는 것을 방지해야 했다.

처음에는 이런 식으로 hero의 x 좌표가 0보다 클 때만 왼쪽으로 가게끔 했는데, 

speed(캐릭터 이동 속도)가 1이면 제대로 동작하지만 속도 값이 크면 영역 밖으로 나가는 현상이 발생했다.

 

 

x좌표가 0보다 크다 해도 이동하는 값이 x좌표보다 크다면 위와 같이 영역 밖으로 캐릭터가 밀려나는 것이다.

x좌표는 0~canvas.width-hero.width, y좌표는 0~canvas.height-hero.width 이어야 한다.

 

if (leftPressed) {
    hero.x -= speed;
    if (hero.x < 0) hero.x = 0;
  }

 

mdn 자료를 참고해서 문제를 해결했다. x좌표가 0보다 작으면, 즉 음수가 되면 x좌표를 0으로 바꾼다.

그러면 speed 값을 높여도 문제없이 동작한다. 내가 생각한 것과 반대로 x좌표가 음수일 때를 고려한 것이다.

문제가 해결되지 않으면 이처럼 반대로 생각해보자.

 

 


 

 

전체 코드

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;

// const center_hero = width / 2 - 8;
const speed = 10;

/** main character object */
let hero = {
  x: 0,
  y: height - 16,
  width: 16,
  height: 16,
  draw() {
    ctx.fillStyle = 'blue';
    ctx.fillRect(hero.x, hero.y, hero.width, hero.height);
  },
};

/** move characters with keyboard event */
let leftPressed = false;
let rightPressed = false;
let upPressed = false;
let downPressed = false;


function keyDown(e) {  
  if (e.code === 'ArrowLeft') {
    leftPressed = true;
    
  } else if (e.code === 'ArrowRight') {
    rightPressed = true;
  } else if (e.code === 'ArrowUp') {
    upPressed = true;
  } else if (e.code === 'ArrowDown') {
    downPressed = true;
  }
}

function keyUp(e) {
  if (e.code === 'ArrowLeft') {
    leftPressed = false;
  } else if (e.code === 'ArrowRight') {
    rightPressed = false;
  } else if (e.code === 'ArrowUp') {
    upPressed = false;
  } else if (e.code === 'ArrowDown') {
    downPressed = false;
  }
}

function move() {
  if (leftPressed) {
    hero.x -= speed;
    if (hero.x < 0) hero.x = 0;
  } else if (rightPressed) {
    hero.x += speed;
    if (hero.x >= width - hero.width) hero.x = width - hero.width;
  } else if (upPressed) {
    hero.y -= speed;
    if (hero.y < 0) hero.y = 0;
  } else if (downPressed) {
    hero.y += speed;
    if (hero.y >= height - hero.height) hero.y = height - hero.height;
  }
  requestAnimationFrame(move);
}

document.addEventListener('keydown', keyDown);
document.addEventListener('keyup', keyUp);
move();

/** draw */
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  hero.draw();
  requestAnimationFrame(draw);
}

draw();

 

 

경쾌하게 키보드로 움직이는 기능 완성!

바닐라 자바스크립트 게임을 만들 예정인데 컨셉이나 내용은 고민 중이다.

게임 개발 꼭 해보고 싶었는데 차근차근 기능 만들어나가야지. 설렌다 헤헷

 

 


 

 

 

참고 자료

 

KeyboardEvent: key property - Web APIs | MDN

The KeyboardEvent interface's key read-only property returns the value of the key pressed by the user, taking into consideration the state of modifier keys such as Shift as well as the keyboard locale and layout.

developer.mozilla.org

 

 

Paddle and keyboard controls - Game development | MDN

This is the 4th step out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson4.html.

developer.mozilla.org

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.