달력

4

« 2024/4 »

  • 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

정확히 말하면, 게임은 아니고 js로도 게임 제작이 가능할 것 같아서 샘플코드 정도를 작성해 본 것.

작성 목적은 Javascript의 객체지향적 활용을 연습할 겸, css 구성원리를 보다 깊이 있게 이해해보기 위함.


javascript는 이벤트 기반으로 동작하기 때문에 루프 기반으로 하지 않아도 될 것 같아서 아래와 같이 만들었다.

동작은 그냥 방향키로 움직이고, 스페이스바로 미사일을 쏘게 되는 단순한 기능만 넣었다.


근데 이 코드 문제가 있다.

화살표 키를 누르면 캐릭터가 부드럽게 움직이지 않고 뚝뚝 끊겨서 움직인다.

이는 사용자마다 키보드 반복 주기 설정 값이 달라서이다.

또한 키보드 동시입력을 체크하기도 어렵다.


결론)

처음엔 event driven 방식으로 해서 성능을 높일 생각이었는데, 제약 사항이 많았다.

그래서 결국 무한루프를 통한 State 검출 방식으로 하는 것이 좋겠다는 결론으로 회귀.


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<!-- jQuery CDN -->

<script src="https://code.jquery.com/jquery-3.1.1.js"></script>

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<style>

#stage{position:relative;width:500px;height:500px;border:solid;background-color:greenyellow}

#hero{position:relative;top:450px;left:230px;width:50px;height:50px;background-color:yellowgreen}

.bullet{position:absolute;width:10px;height:10px;background-color:red;border:solid 1px}

</style>

<script>

function Hero(){

}

Hero.prototype.move = function(direction){

if(direction==37){

$("#hero").css('left', '-=10');

}else if(direction==38){

$("#hero").css('top', '-=10');

}else if(direction==39){

$("#hero").css('left', '+=10');

}else if(direction==40){

$("#hero").css('top', '+=10');

}

}

function Bullet(){

}

Bullet.prototype.shot = function(){

var heroPosX = parseInt($("#hero").css("left")) + 20 + 'px';

var heroPosY = parseInt($("#hero").css("top")) - 10 + 'px';

//var appendBulletTag = '<div class="bullet" style="left:100px; top:100px;"></div>';

var appendBulletTag = '<div class="bullet" style="left:'+heroPosX+'; top:'+heroPosY+'"></div>';

var thisBullet = $("#stage").append(appendBulletTag);

var count = 0;

}

var hero = new Hero();

var bullet = new Bullet();

$(function(){

(function(){

setInterval(function(){

$(".bullet").css('top', '-=5');

}, 30);

})();

$(document).on("keydown", function(e){

console.log(e.keyCode);

if(e.keyCode == 32){

e.preventDefault();

bullet.shot();

}else{

hero.move(e.keyCode);

}

});

})

</script>

</head>

<body>

<div id="stage">

<div id="hero"></div>

</div>

</body>

</html>

:
Posted by 클레잇