Cute Apple
본문 바로가기
개발/HTML&JS

htm 슈팅게임

by 미댕댕 2021. 3. 25.

작업 결과물1

 

 

body, CSS, script 작업

 

1. intro

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<style>
body{
    background: #000000;
}    
 
#wrapper{
    width:700px;
    height:600px;
    border:5px solid yellow;
    margin: auto;
    text-align: center;
} 
#wrapper h1{
    text-align:center;
    color:#FFFFFF;
    font-weight: bold;
    font-size:70px;
}
#container{
    height: 120px;
}
#container p{
    text-align: center;
    color:darkturquoise;
    font-weight: bold;
    font-size:35px;
}
#wrapper button{
    padding:10px;
 
}
 
</style>
<script>
var flag=true;
 
function init(){
    document.querySelector("button").addEventListener("click",function(){
        //메인페이지로 링크
        //a태그를 자바스크립트로 표현한 것이 location.href
        location.href="./횡슈팅게임최종.html";
    });
}
function blink(){
    var vision=(flag)? "none":"block";
    document.querySelector("p").style.display=vision;
    flag=!flag;
}
window.addEventListener("load",function(){
    init();
    setInterval("blink()"500);
});
</script>
</head>
<body>
    <div id="wrapper">
        <h1>Space War</h1>
        <div id="container">
            <p>INSERT COIN</p>
        </div>
        <button>Game Start</button>
    </div>
</body>
</html>
cs

* location.href 를 이용하면 " "안에 있는 경로로 이동을 할 수 있다.

* blink() 함수는 <p> 태그 안에 있는 글자를 삼항 연산자를 이용해서 보였다 안보였다 하게 만들었다.

 

 

 

2. main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<style>
*{margin: 0px;}
#wrapper{
    width: 100%;
    height: 600px;
    background: url("../images/shooting/bg4.jpg");
    position: relative;
    overflow: hidden;
}
#info{
    background: yellow;
    opacity: 0.4;
    position: relative;
 
}
</style>
<script src="../js/Plane.js"></script>
<script src="../js/Bullet.js"></script>
<script src="../js/lib.js"></script>
<script src="../js/Enemy.js"></script>
<script src="../js/Hp.js"></script>
<script src="../js/Item.js"></script>
<script src="../js/ItemRole.js"></script>
 
<script>
var wrapper;
var info;
var plane; //주인공 제어를 위한 전역변수
var bgX=0//배경처리용 변수
var bulletArray=new Array(); //총알 여러개를 가리키기 위한 배열 전역변수
var enemyArray=[];
var enemyImg=["e1.png","e2.png","e3.png","e4.png"]; //적군 여럿을 가리키기 위한 배열 전역변수
var hpArray=new Array();
var itemArray=[];
var itemImg=["bullet.png","bomb.png""hp.png","speed.png"]
var count=0;
var bulletImg=["ball6.png","ball7.png"];
bulletHeight=[1530];
var weaponIndex=0;
var roleArray=[];
var loopFlag=true;
var n=2;
 
 
function init(){
    // constructor(container, src, width, height, x, y)
    wrapper=document.getElementById("wrapper");
    info=document.getElementById("info");
    //게임가동과 동시에 주인공 등장
    createHero();
 
    //피 생성
    createHp();
 
    //게임 가동과 동시에 적군 등장
    createEnemy();
 
    //아이템 정보 생성
    createItemRole();
 
    // body태그에 키보드 이벤트 연결
    document.body.addEventListener("keydown"function(){
        pressDown();
    });
    document.body.addEventListener("keyup",function(){
        pressUp();
    });
 
}
function pressUp(){
    switch(event.keyCode){
        case 37:
            plane.velX=0;break;
        case 39:
            plane.velX=0;break;
        case 38:
            plane.velY=0;break;
        case 40:
            plane.velY=0;break;
    }
}
//키보드 제어 함수 : space bar=총알 , b=폭탄, 아이템공격=i
function pressDown(){
    var key=event.keyCode;
    // console.log("당신이 누른 키의 아스키코드는", key)
 
    // 4가지 조건으로 키보드 제어
    switch(key){
        case 39 :
        plane.velX=n;break;
        case 37 :
        plane.velX=-n;break;
        case 40 :
        plane.velY=n;break;
        case 38 :
        plane.velY=-n;break;
        case 32:
            fire(); break;
        case 27
            loopFlag=!loopFlag; break;
    }
    plane.render(); //렌더링
 
}
//총알 등장
function fire(){
    // constructor(container, src, width, height, x, y, velX, velY)
    bullet=new Bullet(wrapper, "../images/shooting/"+bulletImg[weaponIndex]
    , 30, bulletHeight[weaponIndex], plane.x+(plane.width/2), plane.y+(plane.height/2), 100);
    bulletArray.push(bullet); //총알 배열에 방금 태어난 총알 인스턴스 추가하기
}
//주인공 등장
function createHero(){
    // constructor(container, src, width, height, x, y, velX, velY)
    plane=new Plane(wrapper, "../images/shooting/plane4.png"706010020000);
}
 
//hp 등장
function createHp(){
    // constructor(container, src, width, height, x, y)
    for(var i=0;i<3;i++){
        var hp=new Hp(info,"../images/shooting/heart.png"2020, i*230);
        hpArray.push(hp);
    }
}
 
//적 등장
function createEnemy(){
    // constructor(container, src, width, height, x, y, velX, velY)
    for(var i=0;i<enemyImg.length;i++){
        enemy=new Enemy(wrapper,"../images/shooting/"+enemyImg[getRandom(enemyImg.length)]
        , 80,60,screen.width,50+(i*150),-(getRandom(5)+2),0);
        enemyArray.push(enemy);
    }
}
//아이템 역할 생성
function createItemRole(){
    // constructor(role, src)
    for(var i=0;i<itemImg.length;i++){
        var itemRole=new ItemRole(i, "../images/shooting/"+itemImg[i]);
        roleArray.push(itemRole);
    }
 
}
//아이템 등장(랜덤)
function  createItem(){
    // constructor(itemRole, container, width, height, x, y, velX, velY)
    
    // var n=getRandom(itemImg.length);
    // // console.log("몇번째 아이템?", n);
    // var item=new Item(roleArray[n], wrapper , 30, 30, screen.width+getRandom(100), 50+getRandom(500), -2, 0)
    //     itemArray.push(item);
    
    for(var i=0;i<itemImg.length;i++){
        var item=new Item(roleArray[i], wrapper , 3030, screen.width+getRandom(100), 50+getRandom(500), -20)
        itemArray.push(item);
    }
}
 
//배경처리
function bgEffect(){
    bgX--;
    wrapper.style.backgroundPosition=bgX+"px 0px"
}
//무기교체
function changeWeapon(){
    // console.log("무기교체")
    weaponIndex=1;
}
//적군소멸
function clearEnemy(){
    // console.log("적군소멸")
    var len=enemyArray.length;
    for(var i=0;i<len;i++){
        wrapper.removeChild(enemyArray[0].img);
        enemyArray.splice(0,1);
    }
}
//hp추가
function increaseHp(){
    // console.log("피 생성")
    if(hpArray.length<4){
        var hp=new Hp(info,"../images/shooting/heart.png"2020, hpArray.length*230);
        hpArray.push(hp)
    }
}
//스피드 증가
function speedUp(){
    console.log("스피드 증가")
    n++;
    if(n>=6){
        n=6;
    }
}
 
 
 
 
 
 
//무한루프
function gameLoop(){
    if(loopFlag){
 
        // console.log("심장 뛰어요");
        bgEffect();
    
        plane.tick();//물리량 변화
        plane.render();//그래픽 처리
    
        for(var i=0;i<bulletArray.length;i++){
            bulletArray[i].render();
            bulletArray[i].tick(); //배열 삭제는 여기서 수행되기 때문에 그래픽 먼저 삭제하고 배열을 삭제할 것!
        }
    
        for(var i=0;i<enemyArray.length;i++){
            enemyArray[i].render();
            enemyArray[i].tick(); //배열 삭제는 여기서 수행되기 때문에 그래픽 먼저 삭제하고 배열을 삭제할 것!
        }
    
        for(var i=0;i<itemArray.length;i++){
            itemArray[i].render();
            itemArray[i].tick(); //배열 삭제는 여기서 수행되기 때문에 그래픽 먼저 삭제하고 배열을 삭제할 것!
        }
    
        //아이템이 등장할 시점을 카운터를 세서, 원하는 시간을 interval로 조정
        if(count%600==0){
            createItem();
        }
        //적군 등장 시점
        if(count%300==0){
            createEnemy();
        }
        
        log();
    
        count++
    }
}
 
function log(){
    var str="bullet Count: "+bulletArray.length;
 
    str+=" , Enemy Count: "+enemyArray.length;
 
    // info.innerText=str;
    document.getElementById("status").innerText=str;
}
 
 
 
window.addEventListener("load",function(){
    init();
    setInterval("gameLoop()",10)//fps
})
</script>
</head>
<body>
    <div id="wrapper">
        <div id="info">
            <div id="status" style="margin-left:130px;"></div>
        </div>
    </div>
</body> 
</html>
cs

 

script 작업

* 윈도우가 로드시 init()함수를 호출해 주고 gameLoop()라는 심장을 뛰게 해준다.

 

* 변수

1. init()

* 시작과 동시에 주인공등장, 피생성, 적군등장, 아이템정보생성을 해주는 함수를 생성해준다.

* 이벤트 리스너로 키를 눌렀을때 pressDown() 함수가 호출되고 키에서 손을 뗐을때 pressUp() 함수가 호출된다.

 

2. pressDown(), pressUp()

* pressDown() 함수가 호출되었을 때는 키가 작동되면서 plane의 vel 값들이 전부 0으로 변경되고 pressUp() 함수가 호출되면 plane의 vel 값이 n으로 변경되어 n 만큼 증가된다.

* space bar 를 누르면 fire() 함수를 호출한다.

* esc 키가 눌리게 되면 loopFlag가 true/false로 변경이 되며 심장을 멈추거나 뛰게 할 수 있다. (게임화면 전체를 멈추거나 움직이게 할 수 있다.)

 

3. fire()

* 스페이스바를 누르면 bullet 객체가 생성되면 bulletArray에 생성된 객체를 담아준다. 

* 여기서 src에는 bulletImg[weaponIndex]를 넣어주면서 아이템과 충돌하게 되면 weaponIndex를 변경해주면서 총알이 생성된다.

 

4. createHero(), createHp(), createEnemy(), createItemRole(), createItem()

* 각 객체들을 생성하면서 각각의 배열에 넣어준다.

 

5. changeWeapon(), clearEnemy(), increaseHp(), speedUp()

* 각 아이템을 먹었을때 수행되는 함수이다.

 

6. gameLoop()

* 무한히 수행될 심장역할을 한다.

* 각 클래스들의 tick()과 render()를 호출해준다.

 

 

 

class 작업

1. Plane

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// 비행기라는 사용자 정의 자료형을 선언
class Plane{
    // 변수와 함수
 
    //객체의초기화
    //비행기가 어떤 특성을 가지고 태어날지 결정
    constructor(container, src, width, height, x, y, velX, velY){
        //멤버변수 선언 초기화
        this.container=container; //비행기가 붙을 부모요소
        this.img=document.createElement("img");
        this.src=src;
        this.width=width;
        this.height=height;
        this.x=x;
        this.y=y;
        this.velX=velX;//주인공의 x축으로 속도를 결정
        this.velY=velY;//주인공의 y축으로 속도를 결정
        //멤버 변수를 이용한 속성값 지정(스타일 속성)
        this.img.src=src;
        this.img.style.width=this.width+"px";
        this.img.style.height=this.height+"px";
        this.img.style.position="absolute";
        this.img.style.left=this.x+"px";
        this.img.style.top=this.y+"px";
 
        this.container.appendChild(this.img);
 
    }
    //
    tick(){
        this.x+=this.velX;
        this.y+=this.velY;
        // console.log("this.x=", this.x);
        // console.log("this.y=", this.y);
 
        //화면 밖으로 주인공이 나가지 않게 하기
        if(this.x<=0){
            this.x=0;
        }
        if(this.x>=screen.width-this.width){
            // console.log("경계에 도착");
            this.x=screen.width-this.width;
        }
 
        if(this.y<=0){
            this.y=0;
        }
        if(this.y>= 600-this.height){
            this.y= 600-this.height;
        }
 
        //나와 적군들과 충돌체크, 나의 hp 죽고 적군 죽고
        for(var i=0;i<enemyArray.length;i++){
            if(hitTest(this.img , enemyArray[i].img)){ 
                removeObject(this.container, enemyArray[i].img,  enemyArray, i);
                if(hpArray.length>0){
                    removeObject(info, hpArray[hpArray.length-1].img, hpArray ,hpArray.length-1);//나의 hp제거 
                }
                //주인공의 에너지가 모두 소진되었는지 hp배열의 길이가 0이면
                if(hpArray.length==0){
                    var div=document.createElement("div");
                    div.style.fontSize=150+"px";
                    div.style.textAlign="center";
                    div.style.color="#FFF";
                    div.style.fontWeight="bold";
                    div.style.height=600+"px"
                    div.innerHTML="GAME OVER <br><a href=\"javascript:location.reload();\">Retry</a>";
                    this.container.appendChild(div)//생성된 div를 화면에 부착
                }
            }
        }
 
        /*
        role 0) 무기를 미사일로 전환
        role 1) 또다른 무기로 미사일로 전환 missile2.png
        role 2) hp추가
        role 3) 주인공의 속도 업그레이드
        */
        //나와 아이템 충돌검사(아이템 취득)
        for(var i=0;i<itemArray.length;i++){
            if(hitTest(this.img, itemArray[i].img)){
                var itemRole=itemArray[i].itemRole;//주인공과 충동할 아이템정보
 
                removeObject(this.container, itemArray[i].img, itemArray, i)
                //조건을은 롤을 통해 처리 가능
                switch(itemRole.role){
                    case 0
                    changeWeapon() ;break;
                    case 1
                    clearEnemy() ;break;
                    case 2
                    increaseHp() ;break;
                    case 3
                    speedUp();break;
                }
            }
        }
 
    }
    //변경된 값을 화면에 보여주기 위한 그래픽 처리(게임분야, 그래픽 분야에서는 랜더링)
    render(){
        this.img.style.left=this.x+"px";
        this.img.style.top=this.y+"px";
    }
}
cs

* 주인공을 등장시키기 위해 주인공 틀을 생성해준다.

* (containersrcwidthheightxyvelXvelY)를 매개변수로 받아 주인공을 생성한다.

* constructor 안에는 멤버 변수와 멤버변수를 이용한 속성값을 지정해준다.

 

* tick() 메서드에는 주인공의 행동에대한 모든 조건들이 들어있다.

  - x축과 y축 좌표에 velX,Y 값을 더해주고 그 값을 x,y 축의 값으로 바꿔준다.

  - if문을 활용하여 x,y 좌표를 화면 밖으로 나가지 않게 제어한다.

  - screen.width 속성을 이용하면 스크린의 너비를 지정할 수 있다.

 

  - for문을 적의 수 만큼 돌면서 만약에 hitTest함수의 나와 적들을 만나게 된다면 적들을 removeObject로 제거하고 만약 hpArray가 0보다 크다면 하트를 제거해준다.

  - 그릐고 만약에 hpArray의 길이가 0이라면 "GAME OVER"라는 <div>를 띄워주며 그 밑에 location.reload() 내장메서드를 이용하여 리셋버튼을 생성해준다.

 

  - for문을 아이템 수 만큼 돌면서 만약 나와 아이템이 만나게되면  우선 itemArray에 있는 itemRole을 변수에 담아주고 아이템을 제거해준다.

  - 그리고 switch 문을 돌면서 itemRole의 role의 번호가 바뀔때마다 각 함수들을 수행하게 하였다. (함수는 main에 구성되어있다)

 

* render() 메서드는 tick()에 의해 적용된 x, y 값들을 img 의 위치에 실제로 적용하여 화면에 나타내 주기위하여 생성하였다.

 

 

 

 

2. Bullet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//총알을 정의한다
class Bullet{
    constructor(container, src, width, height, x, y, velX, velY){
        //멤버변수
        this.container=container;
        this.img=document.createElement("img");
        this.src=src;
        this.width=width;
        this.height=height;
        this.x=x;
        this.y=y;
        this.velX=velX;
        this.velY=velY;
 
        //총알의 모습
        this.img.src=this.src;
        //크기
        this.img.style.width=this.width+"px";
        this.img.style.height=this.height+"px";
        //위치
        this.img.style.position="absolute";
        this.img.style.left=this.x+"px";
        this.img.style.top=this.y+"px";
 
        this.container.appendChild(this.img);
    }
    //물리량 변화
    tick(){
        this.x+=this.velX;
        this.y+=this.velY;
 
        //나(총알)와 적군과의 충돌체크 (총알인 나와 적군은 1대 다 관계이다.)
        //만일 적군과 총알인 내가 충돌한다면, 제거대상은 적군과 나 둘다 해당
        for(var i=0;i<enemyArray.length;i++){
            var hitResult=hitTest(this.img, enemyArray[i].img); //객체 자체는 무형의 단위일뿐 style을 가질 수 없다.
 
            if(hitResult){
                removeObject(this.container, enemyArray[i].img, enemyArray, i);
                removeObject(this.container, this.img, bulletArray, bulletArray.indexOf(this))
            }
        }
 
 
        //총알은 날아가다가, 자신이 스크린을 벗어난다면, 자살
        if(this.x>screen.width){
            // 여기서 this는 bullet 객체가 생성되었을때 나를 지칭함
            var index=bulletArray.indexOf(this);
            removeObject(this.container, this.img, bulletArray, index);
        }
    }
    //그래픽 처리
    render(){
        this.img.style.left=this.x+"px";
        this.img.style.top=this.y+"px"
    }
}
cs

* constructor는 Plane 클래스와 거의 동일하게 설정해 준다.

* for문을 적의 수만큼 돌면서 만약에 hitTest 함수가 true를 반환한다면 적군과 총알을 모두 제거한다.

 

* 그리고 만약에 총알이 스크린너비를 넘어가면 총알을 제거한다.

 

* render()메서드로 총알의 x,y 위치를 적용시켜준다.

 

 

 

 

3. Enemy

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 적군을 정의
class Enemy{
    constructor(container, src, width, height, x, y, velX, velY){
        //멤버변수
        this.container=container;
        this.img=document.createElement("img");
        this.src=src;
        this.width=width;
        this.height=height;
        this.x=x;
        this.y=y;
        this.velX=velX;
        this.velY=velY;
        this.r=0;
 
        //적군의 모습
        this.img.src=this.src;
        //크기
        this.img.style.width=this.width+"px";
        this.img.style.height=this.height+"px";
        //위치
        this.img.style.position="absolute";
        this.img.style.left=this.x+"px";
        this.img.style.top=this.y+"px";
 
        this.container.appendChild(this.img);
    }
    tick(){
        this.x+=this.velX;
        this.y+=this.velY;
 
        if(this.x<0){
            removeObject(this.container, this.img, enemyArray, enemyArray.indexOf(this));
        }
    }
    render(){
        this.img.style.left=this.x+"px";
        this.img.style.top=this.y+"px";
        this.r++;
        this.img.style.transform="rotate("+this.r+"deg)";
 
    }
}
cs

* constructor는 plane과  거의 동일하다.

* 적의 x,y 값에 velX,Y를 더해준다.

* 만약에 x값이 0보다 작아진다면 적을 제거해준다.

* render() 메서드에 실제로 적용되는 값들을 넣어준다.

 

 

 

4. Hp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Hp{
 
    constructor(container, src, width, height, x, y){
        //멤버변수
        this.container=container;
        this.img=document.createElement("img");
        this.src=src;
        this.width=width;
        this.height=height;
        this.x=x;
        this.y=y;
 
        //하트의 모습
        this.img.src=this.src;
        //크기
        this.img.style.width=this.width+"px";
        this.img.style.height=this.height+"px";
        //위치
        this.img.style.position="absolute";
        this.img.style.left=this.x+"px";
        this.img.style.top=this.y+"px";
 
        this.container.appendChild(this.img);
    }
 
}
cs

* constructor 는 plane과 동일하다.

 

 

 

5. Item

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 아이템 정의
/*
role 1 : candy1.png) 무기 전환
role 2 : candy2.png) 적군 전체 소멸
role 3 : candy3.png) hp추가
role 4 : candy4.png) 주인공의 속도 업그레이드
*/
 
class Item{
    constructor(itemRole, container, width, height, x, y, velX,velY){
        this.itemRole=itemRole; //각 아이템을 보유할 객체
        this.container=container;
        this.img = document.createElement("img");
        this.src=itemRole.src;
        this.width=width;
        this.height =height;
        this.x=x;  
        this.y=y;
        this.velX=velX; 
        this.velY=velY;
 
        //아이템의 모습을 설정해본다!!
        this.img.src=this.src;
        
        //크기
        this.img.style.width=this.width+"px";
        this.img.style.height=this.height+"px";
 
        //위치
        this.img.style.position="absolute";
        this.img.style.left=this.x+"px";
        this.img.style.top=this.y+"px";
 
        //부모요소에 부착
        this.container.appendChild(this.img);
   }
    tick(){
        this.x += this.velX;
        this.y += this.velY;
 
        //내가 화면의 음수값을 가질때 즉 좌측 한계점을 지나면, 제거
        if(this.x<0){
            removeObject(this.container, this.img, itemArray, itemArray.indexOf(this));
        }
   }
    render(){
        this.img.style.left=this.x+"px";
        this.img.style.top=this.y+"px";
    }
}
cs

* constructor 는 plane과 거의 동일하고 itemRole이 추가되었다.

* img.src에는 itemRole 클래스에 있는 src를 넣어준다.

 

* tick()메서드 안에는 x,y축에 velX,Y축을 더해주고 x의 값이 0보다 작으면 아이템을 제거해준다.

* render()메서드에는 실제로 적용되는 값을 대입해준다.

 

 

 

 

5. ItemRole

1
2
3
4
5
6
7
8
9
/* 각 아이템이 어떤 역할을 하고, 어떤 이미지를 갖고 있는지 대한 정보를
가진 객체 정의 */
// 디자인적으로 또는 시작적으로 보여지는 클래스가 아니라, 아이템의 정보를 가진 객체
class ItemRole{
    constructor(role, src){
        this.role=role;
        this.src=src;
    }
}
cs

* 각 아이템들의 정보를 담아줄 객체를 생성한다.

반응형

'개발 > HTML&JS' 카테고리의 다른 글

html 플랫포머 게임  (0) 2021.04.04
html JSON 활용  (0) 2021.03.30
html 충돌검사  (0) 2021.03.24
html 객체와 class  (0) 2021.03.23
html 다차원 배열2  (0) 2021.03.18

댓글