본문 바로가기

Front-End/JavaScript

[JavaScript]키보드로 움직이는 자동차 만들기

~ 목차 ~

기본적인 HTML, CSS, JavaScript로 자동차를 움직이게 만들고 싶어져 만들어 봤다.

물론, GPT의 도움을 받아서 만들어 보았다.

간단하게 JS로 만들 수 있다.🪄

<!DOCTYPE html>
<html>
<head>
    <title>자동차 시뮬레이션</title>
</head>
<body>
  
    <div id="tank" style="position: relative;">
      <img src="/iconcar.png" style="width: 50px; height: 50px; position: absolute; top: 0; left: 0;">
    </div>
    <script>

        const tankElement = document.getElementById('tank');
        const tankImage = tankElement.querySelector('img');
        const tank = { x: 0, y: 0, direction: 'right' };

        // 키보드 이벤트 리스너 등록
        window.addEventListener('keydown', handleKeyDown);

        function handleKeyDown(event) {
            switch (event.key) {
                case 'ArrowUp':
                    moveUp(tank, tankImage);
                    break;
                case 'ArrowLeft':
                    moveLeft(tank, tankImage);
                    break;
                case 'ArrowRight':
                    moveRight(tank, tankImage);
                    break;
                case 'ArrowDown':
                    moveDown(tank, tankImage);
                break;
            }
        }

        function moveUp(tank, tankImage) {
          tank.direction = 'up';
            tank.y -= 50;
            tankImage.style.top = tank.y + 'px';
        }

        function moveLeft(tank, tankImage) {
          tank.direction = 'left';
            tank.x -= 50;
            tankImage.style.left = tank.x + 'px';
        }

        function moveRight(tank, tankImage) {
          tank.direction = 'right';
            tank.x += 50;
            tankImage.style.left = tank.x + 'px';
        }
        function moveDown() {
          tank.direction = 'down';
            tank.y += 50;
            tankImage.style.top = tank.y + 'px';
        }
    </script>
</body>
</html>

 

※ 일반적으로  웹 페이지의 좌표 시스템에서 Y 축은 아래로 갈수록 증가하는 값이라 위로 가려면 tank.y -= 50;을 해줘야 한다.


결과

움직이지 않을때
키보드 오른쪽 방향 눌렀을 때
아래 버튼 눌렀을 때
왼쪽버튼 눌렀을 때

 

728x90

'Front-End > JavaScript' 카테고리의 다른 글

[JavaScript]탱크 언어 시뮬레이션 만들기  (0) 2023.11.01