Javascript Constructor Function
Javascript Constructor Function example
Javascript 에서 생성자 함수를 선언하고 다수개의 인스턴스를 생성 및 사용하는 예
[HTML5 Canvas를 이용한 간단한 슈팅게임의 원리이해]
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Javascript Constructor Function</title>
<style type="text/css">
canvas { border:1px solid black;}
</style>
<script type="application/javascript">
var ctx;
var canvas;
var missile;
var gun;
var intval;
var inuseArr = new Array();
var reuseArr = new Array();
function Missile(ctx,x,y, speedX, speedY) {
this.ctx = ctx;
this.x = x;
this.y = y;
this.speedX = speedX;
this.speedY = speedY;
this.move = function() {
this.x += this.speedX;
this.y += this.speedY;
this.draw();
if(this.y<0) { //canvas를 벗어난 공은 재활용을 위해 reuseArr에 저장한다
var idx = inuseArr.indexOf(this);
reuseArr.push(inuseArr.splice(idx,1)[0]);
}
}
this.draw = function() {
this.ctx.beginPath();
this.ctx.fillStyle = 'black';
this.ctx.arc(this.x, this.y, 5, 0, (Math.PI/180)*360, false);
this.ctx.fill();
}
}
function Gun(ctx,x,y) {
this.ctx = ctx;
this.x = x;
this.y = y;
this.move = function(x,y) {
this.x = x;
this.y = y;
}
this.draw = function() {
this.ctx.beginPath();
this.ctx.fillStyle = 'black';
this.ctx.fillRect(this.x-5,300-40, 10, 40);
this.ctx.fill();
}
this.fire = function() {
if(reuseArr.length==0) {//재활용을 위해 저장된 공이 없는 경우에는 새로 생성한다
inuseArr.push(new Missile(this.ctx, this.x, 300-40, 0, -10));
}else { //재활용할 공이 있는 경우에는 새로 생성하지 않고 재사용한다
var missile = reuseArr.pop();
missile.x = this.x;
missile.y = 300-40;
inuseArr.push(missile);
}
}
}
function init() {
if(intval!=null) {
alert('게임이 이미 시작되었습니다');
return;
}
canvas = document.getElementById("canvas1");
window.addEventListener("keydown", onKeyDown);
window.addEventListener("mousemove", onMouseMove);
if(!canvas.getContext) {
alert('Canvas 그리기를 지원하는 브라우저가 아닙니다');
return;
}
ctx = canvas.getContext('2d');
gun = new Gun(ctx, 200,300);
intval = setInterval(function(){drawFrame();}, 50);
}
function drawFrame() {
ctx.clearRect(0,0,canvas.width,canvas.height);
gun.draw();
for(var i=0;i<inuseArr.length;i++) {
try{
inuseArr[i].move();
}catch(err) {
console.log(err);
return;
}
}
}
function onKeyDown(event) {
var keyCode = 0;
if(event==null) {
keyCode = window.keyCode
window.event.preventDefault();
//alert("이벤트 1:"+keyCode);
}else{
keyCode = event.keyCode;
event.preventDefault();
//alert("이벤트 2:"+keyCode);
}
switch(keyCode){
case 32: // space key
gun.fire();
break;
case 37: // left key
break;
case 38: // up key
break;
case 39: // right key
break;
case 40: // down key
break;
default:
break;
}
}
function onMouseMove(event) {
//마우스의 스크린 위치를 캔바스 좌표로 보정한다
var rect = canvas.getBoundingClientRect();
var x = event.clientX - rect.left;
var y = event.clientY - rect.top;
gun.move(x,y);
}
</script>
</head>
<body>
<canvas id="canvas1" width="400" height="300"></canvas>
<br>
마우스로 조준하고 SPACE 키를 누르면 공이 발사된다<br>
<input type="button" value="START" onclick="init();">
</body>
</html>