[JQuery] keyboard event 활용하여 캐릭터 움직이기

2022. 6. 3. 09:08Programming의 세계/JavaScript

다음과 같이 키보드 방향키에 따라 캐릭터가 움직있게 하는 기능을 수행하고자 한다. 

keydown은 다음과 같이 작동한다.(w3school를 통한 예시)

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("input").keydown(function(){
    $("input").css("background-color", "yellow");
  });
  $("input").keyup(function(){
    $("input").css("background-color", "pink");
  });
});
</script>
</head>
<body>

Enter your name: <input type="text">

<p>Enter your name in the input field above. It will change background color on keydown and keyup.</p>

</body>
</html>

<결과창>

다음과 같은   $("변수").keydown(function(){~ 방법으로 풀면 되겠다.

 

1. <html>에서 테두리 지정 및 캐릭터 삽입

(캐릭터 크기 : width/height = 200px, 테두리 크기 : width/height = 600px, 

    <div id="container">
        <img id="bob" src="../assets/bob.gif" alt="minions">
    </div>

2. <script> 변수 지정

        let bob = $('#bob');
        const GAME_WIDTH = 600;
        const GAME_HEIGHT = 600;
        const MOVE = 25;
        const BOB_HEIGHT = 200;
        const BOB_WIDTH = 200;

3. 숫자로 변환하여 테두리에 맞추어 바닥과 우측 끝 계산

 	$('body').keydown(function (event) {
            let top = Number(bob.css('top').replace('px', ''));
            let bottom = top + BOB_HEIGHT;
            let left = Number(bob.css('left').replace('px', ''));
            let right = left + BOB_WIDTH;

4. switch 활용하여 boundary 밖에서 move 제한 주기

 			switch (event.key) {
                case 'ArrowUp':
                    if (top - MOVE < 0) {
                        return;
                    }
                    bob.css({ top: '-=25px' });
                    break;
                    
                case 'ArrowDown':
                    if (bottom + MOVE > GAME_HEIGHT) {
                        return;
                    }
                    bob.css({ top: '+=25px' });
                    break;
                    
                case 'ArrowRight':
                    if (right + MOVE > GAME_WIDTH) {
                        return;
                    }
                    bob.css({ left: '+=25px' });
                    break;
                    
                case 'ArrowLeft':
                    if (left - MOVE < 0) {
                        return;
                    }
                    bob.css({ left: '-=25px' });
                    break;
           		 	}
       		 });

하면 잘 작동된다.

 

 

 

D.O.N.E!!