게임 움직임
게임 회전 장절에서 설명한 새로운 방식으로 컴포넌트를 그리면, 동작이 더 유연해집니다.
물체를 어떻게 이동시키나요?
를 추가하면, component
구조 함수에 속도
속성을 추가하여, 이는 컴포넌트의 현재 속도를 나타냅니다.
속성에 따라 newPos()
메서드를 변경하여, 속도
와 angle
를 통해 컴포넌트의 위치를 계산합니다.
기본적으로, 컴포넌트는 위쪽을 향하고 있으며, 속도
속성을 1로 설정하면, 컴포넌트가 앞으로 이동하기 시작합니다.
예제
function component(width, height, color, x, y) { this.gamearea = gamearea; this.width = width; this.height = height; this.angle = 0; this.speed = 1; this.x = x; this.y = y; this.update = function() { ctx = myGameArea.context; ctx.save(); ctx.translate(this.x, this.y); ctx.rotate(this.angle); ctx.fillStyle = color; ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height); ctx.restore(); } this.newPos = function() { this.x += this.speed * Math.sin(this.angle); this.y -= this.speed * Math.cos(this.angle); } }
전환
우리는 또한 좌회전과 우회전을 할 수 있기를 원합니다. moveAngle
의 새 속성에 따라, 이는 현재 이동 값이나 회전 각도를 나타냅니다. newPos()
메서드에서 moveAngle
속성 계산 angle
:
예제
moveangle 속성을 1로 설정해 보세요:
function component(width, height, color, x, y) { this.width = width; this.height = height; this.angle = 0; this.moveAngle = 1; this.speed = 1; this.x = x; this.y = y; this.update = function() { ctx = myGameArea.context; ctx.save(); ctx.translate(this.x, this.y); ctx.rotate(this.angle); ctx.fillStyle = color; ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height); ctx.restore(); } this.newPos = function() { this.angle += this.moveAngle * Math.PI / 180; this.x += this.speed * Math.sin(this.angle); this.y -= this.speed * Math.cos(this.angle); } }
키보드를 사용하다
키보드를 사용할 때 빨간 사각형은 어떻게 움직이나요? '위' 방향키를 누를 때, 빨간 사각형은 위로와 아래로 움직이지 않고, 한쪽에서 다른쪽으로 이동하며, 왼쪽과 오른쪽 방향키를 누를 때는 좌우로 회전합니다.
예제
게임 영역에 포커스를 맞추고, 다음과 같이 방향 키를 사용하여 빨간 장애물을 이동하세요.