게임 컨트롤러
버튼을 누르면 빨간 상자를 이동시킬 수 있습니다:
모든 것을 통제하다
이제 빨간 상자를 제어해야 합니다.
위, 아래, 왼쪽, 오른쪽으로 네 개의 버튼을 추가합니다.
각 버튼에 대해 함수를 작성하여 선택된 방향으로 컴포넌트를 이동시킵니다.
을 component
생성자에 두 개의 새로운 속성을 생성하고 이름을 speedX
와 speedY
속성을 사용하여 속도 지시자로 사용됩니다.
을 component
생성자에 새로운 이름을 붙여 newPos()
의 함수는 다음과 같이 사용됩니다: speedX
와 speedY
속성을 변경하여 컴포넌트 위치를 설정합니다.
드로잉 컴포넌트 전에, updateGameArea
함수 호출 newPos
함수:
实例
<script> function component(width, height, color, x, y) { this.width = width; this.height = height; this.speedX = 0; this.speedY = 0; this.x = x; this.y = y; this.update = function() { ctx = myGameArea.context; ctx.fillStyle = color; ctx.fillRect(this.x, this.y, this.width, this.height); } this.newPos = function() { this.x += this.speedX; this.y += this.speedY; } } function updateGameArea() { myGameArea.clear(); myGamePiece.newPos(); myGamePiece.update(); } function moveup() {}} myGamePiece.speedY -= 1; } function movedown() { myGamePiece.speedY += 1; } function moveleft() { myGamePiece.speedX -= 1; } function moveright() { myGamePiece.speedX += 1; } </script> <button onclick="moveup()">UP</button> <button onclick="movedown()">DOWN</button> <button onclick="moveleft()">LEFT</button> <button onclick="moveright()">RIGHT</button>
이동 중지
필요하다면, 버튼을 떼 때 빨간 사각형을 멈추게 할 수 있습니다.
속도 인디케이터를 0으로 설정하는 함수를 추가합니다.
일반 스크린과 터치 스크린을 대비하여, 이 두 가지 장치에 대한 코드를 추가합니다:
实例
function stopMove() { myGamePiece.speedX = 0; myGamePiece.speedY = 0; } </script> <button onmousedown="moveup()" onmouseup="stopMove()" ontouchstart="moveup()">UP</button> <button onmousedown="movedown()" onmouseup="stopMove()" ontouchstart="movedown()">DOWN</button> <button onmousedown="moveleft()" onmouseup="stopMove()" ontouchstart="moveleft()">LEFT</button> <button onmousedown="moveright()" onmouseup="stopMove()" ontouchstart="moveright()">RIGHT</button>
키보드를 컨트롤러로 사용합니다
우리는 방향키를 사용하여 빨간 사각형을 제어할 수 있습니다.
특정 키가 눌렸는지 확인하는 메서드를 생성합니다. myGameArea
객체의 key
속성을 설정합니다. 키보드 코드입니다. 키를 떼 때, key
속성을 설정합니다 false
:
实例
var myGameArea = { canvas : document.createElement("canvas"), start : function() { this.canvas.width = 480; this.canvas.height = 270; this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]); this.interval = setInterval(updateGameArea, 20); window.addEventListener('keydown', function (e) { myGameArea.key = e.keyCode; }) window.addEventListener('keyup', function (e) { myGameArea.key = false; }) }, clear : function(){ this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); } }
그래서, 방향 키 중 하나를 누르면 빨간 박스를 이동할 수 있습니다:
实例
function updateGameArea() { myGameArea.clear(); myGamePiece.speedX = 0; myGamePiece.speedY = 0; if (myGameArea.key && myGameArea.key == 37) {myGamePiece.speedX = -1; } if (myGameArea.key && myGameArea.key == 39) {myGamePiece.speedX = 1; } if (myGameArea.key && myGameArea.key == 38) {myGamePiece.speedY = -1; } if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; } myGamePiece.newPos(); myGamePiece.update(); }
여러 개의 키를 누른 후
여러 개의 키를 누른 경우
여러 개의 키를 동시에 누르면 어떻게 될까요?
위의 예제에서, 컴포넌트는 수직 또는 수평으로만 이동할 수 있습니다. 지금은 컴포넌트가 대각선으로도 이동할 수 있도록 하고 싶습니다. myGameArea
객체를 생성합니다 keys
배열에 각 키를 추가하고 값을 설정합니다 true
까지 true 값을 유지합니다. 더 이상 키를 누르지 않을 때까지 이 값이 keyup
이벤트 리스너 함수에서 변경됩니다 false
:
实例
var myGameArea = { canvas : document.createElement("canvas"), start : function() { this.canvas.width = 480; this.canvas.height = 270; this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]); this.interval = setInterval(updateGameArea, 20); window.addEventListener('keydown', function (e) { myGameArea.keys = (myGameArea.keys || []); myGameArea.keys[e.keyCode] = true; }) window.addEventListener('keyup', function (e) { myGameArea.keys[e.keyCode] = false; }) }, clear : function(){ this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); } } function updateGameArea() { myGameArea.clear(); myGamePiece.speedX = 0; myGamePiece.speedY = 0; if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -1; } if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 1; } if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -1; } if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 1; } myGamePiece.newPos(); myGamePiece.update(); }
마우스 커서를 컨트롤러로 사용하세요
마우스 커서로 빨간 사각형을 제어하려면, myGameArea
객체에 메서드를 추가하여 마우스 커서의 x와 y 좌표를 업데이트합니다:
实例
var myGameArea = { canvas : document.createElement("canvas"), start : function() { this.canvas.width = 480; this.canvas.height = 270; this.canvas.style.cursor = "none"; //원래 커서 숨기기 this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]); this.interval = setInterval(updateGameArea, 20); window.addEventListener('mousemove', function (e) { myGameArea.x = e.pageX; myGameArea.y = e.pageY; }) }, clear : function(){ this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); } }
그런 다음, 마우스 커서로 빨간 사각형을 이동할 수 있습니다:
实例
function updateGameArea() { myGameArea.clear(); if (myGameArea.x && myGameArea.y) { myGamePiece.x = myGameArea.x; myGamePiece.y = myGameArea.y; } myGamePiece.update(); }
스크린을 터치하여 게임을 제어하세요
우리는 터치 스크린에서 빨간 사각형을 제어할 수 있습니다.
을 myGameArea
객체에 메서드를 추가하여 스크린 터치 위치의 x와 y 좌표를 사용합니다:
实例
var myGameArea = { canvas : document.createElement("canvas"), start : function() { this.canvas.width = 480; this.canvas.height = 270; this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]); this.interval = setInterval(updateGameArea, 20); window.addEventListener('touchmove', function (e) { myGameArea.x = e.touches[0].screenX; myGameArea.y = e.touches[0].screenY; }) }, clear : function(){ this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); } }
그런 다음, 사용자가 스크린을 터치할 때, 마우스 커서와 같은 코드로 빨간 사각형을 이동할 수 있습니다:
实例
function updateGameArea() { myGameArea.clear(); if (myGameArea.x && myGameArea.y) { myGamePiece.x = myGameArea.x; myGamePiece.y = myGameArea.y; } myGamePiece.update(); }
캔버스의 컨트롤러
우리는 캔버스에 자신의 버튼을 그려서 컨트롤러로 사용할 수 있습니다:
实例
function startGame() { myGamePiece = new component(30, 30, "red", 10, 120); myUpBtn = new component(30, 30, "blue", 50, 10); myDownBtn = new component(30, 30, "blue", 50, 70); myLeftBtn = new component(30, 30, "blue", 20, 40); myRightBtn = new component(30, 30, "blue", 80, 40); myGameArea.start(); }
특정 컴포넌트(이 예제에서는 버튼)가 클릭되었는지 확인하는 새로운 함수를 추가합니다.
먼저 마우스 버튼이 클릭되었는지 확인하는 이벤트 리스너를 추가합니다.mousedown
와 mouseup
)。터치스크린을 대비하여, 화면이 클릭되었는지 확인하는 이벤트 리스너를 추가해야 합니다.touchstart
와 touchend
):
实例
var myGameArea = { canvas : document.createElement("canvas"), start : function() { this.canvas.width = 480; this.canvas.height = 270; this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]); this.interval = setInterval(updateGameArea, 20); window.addEventListener('mousedown', function (e) { myGameArea.x = e.pageX; myGameArea.y = e.pageY; }) window.addEventListener('mouseup', function (e) { myGameArea.x = false; myGameArea.y = false; }) window.addEventListener('touchstart', function (e) { myGameArea.x = e.pageX; myGameArea.y = e.pageY; }) window.addEventListener('touchend', function (e) { myGameArea.x = false; myGameArea.y = false; }) }, clear : function(){ this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); } }
지금 myGameArea
객체는 클릭된 x와 y 좌표를 알려주는 속성을 가지고 있습니다. 이 속성을 사용하여 우리의 어떤 파란 버튼에서 클릭이 이루어졌는지 확인합니다.
이 새로운 메서드는 clicked
이는 component
구조 함수의 하나의 메서드는 컴포넌트가 클릭되었는지 확인합니다.
을 updateGameArea
함수 내에서, 파란 버튼 중 하나를 클릭하면 필요한 작업을 수행합니다:
实例
function component(width, height, color, x, y) { this.width = width; this.height = height; this.speedX = 0; this.speedY = 0; this.x = x; this.y = y; this.update = function() { ctx = myGameArea.context; ctx.fillStyle = color; ctx.fillRect(this.x, this.y, this.width, this.height); } this.clicked = function() { var myleft = this.x; var myright = this.x + (this.width); var mytop = this.y; var mybottom = this.y + (this.height); var clicked = true; if ((mybottom < myGameArea.y) || (mytop > myGameArea.y) || (myright < myGameArea.x) || (myleft > myGameArea.x)) { clicked = false; } return clicked; } } function updateGameArea() { myGameArea.clear(); if (myGameArea.x && myGameArea.y) { if (myUpBtn.clicked()) { myGamePiece.y -= 1; } if (myDownBtn.clicked()) { myGamePiece.y += 1; } if (myLeftBtn.clicked()) { myGamePiece.x += -1; } if (myRightBtn.clicked()) { myGamePiece.x += 1; } } myUpBtn.update(); myDownBtn.update(); myLeftBtn.update(); myRightBtn.update(); myGamePiece.update(); }