게임 컨트롤러


버튼을 눌러 빨간색 사각형을 이동합니다.








통제권 확보

이제 우리는 빨간색 사각형을 제어하려고 합니다.

위, 아래, 왼쪽, 오른쪽 4개의 버튼을 추가합니다.

선택한 방향으로 컴포넌트를 이동시키는 각 버튼에 대한 함수를 작성하십시오.

component생성자 에서 두 개의 새 속성을 만들고 speedXspeedY. 이러한 속성은 속도 표시기로 사용됩니다.

및 속성을 사용 하여 구성 요소의 위치를 ​​변경하는 이라는 함수를 component생성자 에 추가합니다. newPos()speedXspeedY

newpos 함수는 구성 요소를 그리기 전에 updateGameArea 함수에서 호출됩니다.

예시

<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>

컨트롤러로서의 키보드

키보드의 화살표 키를 사용하여 빨간색 사각형을 제어할 수도 있습니다.

키가 눌렸는지 확인하는 메소드를 생성하고 객체의 key 속성을 myGameArea키 코드로 설정합니다. 키를 놓으면 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();
}

여러 키 누름

두 개 이상의 키를 동시에 누르면 어떻게 됩니까?

위의 예에서 구성 요소는 가로 또는 세로로만 이동할 수 있습니다. 이제 구성 요소도 대각선으로 이동하기를 원합니다.

객체에 대한 keys 배열 을 만들고 myGameArea누른 각 키에 대해 하나의 요소를 삽입하고 값 true을 지정합니다. 키를 더 이상 누르지 않을 때까지 값은 true로 유지되고 값은 falsekeyup 이벤트 리스너 함수에 있게 됩니다.

예시

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"; //hide the original cursor
    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();
}

구성 요소(이 경우에는 버튼)가 클릭되었는지 파악하는 새 기능을 추가합니다.

먼저 이벤트 리스너를 추가하여 마우스 버튼이 클릭되었는지 확인합니다( mousedownmouseup). 터치 스크린을 처리하려면 이벤트 리스너도 추가하여 화면이 클릭되었는지 확인하십시오( touchstarttouchend).

예시

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();
}