-
23_11_23 JS공부정리개발공부/JavaScript 2023. 11. 24. 01:22
[코딩애플] Part 3
게임만드는법
1.화면에 네모,원 그릴수 있어야함
2.프레임마다 코드실행이 가능해야함(1초에 60번) : requestAnimationFrame()
3.collision check할수있어야함(충돌시 코드실행-JS로 간단한 게임만드는 코드
const canvas = document.querySelector('#canvas');const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth - 100;canvas.height = window.innerHeight - 100;
const img1 = new Image();const img2 = new Image();img1.src = 'dinosaur.png'img2.src = 'cactus.png'
const dino = {x : 10,y : 200,width : 50,height : 50,draw(){// ctx.fillStyle = 'green';// ctx.fillRect(this.x,this.y,this.width,this.height);ctx.drawImage(img1,this.x,this.y)},
}dino.x += 1dino.draw()
class Cactus {constructor() {this.x = 500;this.y = 200;this.width = 50;this.height = 50;}draw(){// ctx.fillStyle = 'red';// ctx.fillRect(this.x,this.y,this.width,this.height);ctx.drawImage(img2,this.x,this.y); //img 넣는 함수.}}
let timer = 0;let cactusArray = [];let jumpTimer = 0;let animation;
let jumpFlag = false;function animationFunction() {animation = requestAnimationFrame(animationFunction) //1초에 60번실행시켜주는 함수timer++;ctx.clearRect(0,0,canvas.width,canvas.height)
if (timer % 120 === 0) {let cactus = new Cactus();cactusArray.push(cactus); //장애물여러개 만들때 array에 넣어서 관리.}cactusArray.forEach((a,i,o)=> { //o는 전체배열을 의미a.x-= 2;if(a.x < -30) { //x좌표가 0미만이면 제거o.splice(i,1)}
crashConfirm(dino, a) //모든 장애물과 해야하기떄문에 forEach문안에 넣음a.draw();})if(jumpFlag) { //점프기능dino.y -= 2;jumpTimer++;}if(jumpTimer > 50) {jumpFlag = false;jumpTimer = 0;}if(!jumpFlag && dino.y<200) {dino.y += 2;}dino.draw();}
animationFunction();
function crashConfirm(dino, cactus) {let xdiff = cactus.x -(dino.x+dino.width)let ydiff = cactus.y -(dino.y+dino.height)if( xdiff < -5 && ydiff < -5) {ctx.clearRect(0,0,canvas.width,canvas.height);cancelAnimationFrame(animation);alert('게임종료');}}
document.addEventListener('keydown', function(event){if(event.code === 'Space') {jumpFlag = true;}})수정사항
0. 이미지 크기 히트박스안으로 조정?
1. 점프 여러번 금지?
2. 공룡이 달리는 것처럼 보이게?
3. 배경 다가오는건?
4. 장애물이 나타나는 간격을 랜덤하게?
5. 점수표기는?
6. 시간 지날 때 점수도 오르는 기능은?'개발공부 > JavaScript' 카테고리의 다른 글
23_11_22 JS공부정리 (2) 2023.11.23 23_11_21 JS공부정리 (0) 2023.11.21 23_11_20 JS공부정리 (1) 2023.11.21 23_11_19 JS공부정리 (0) 2023.11.19 23_11_18 JS공부정리 (0) 2023.11.19