javascript로 슈팅 게임 만들기 - 미사일 및 테두리 추가 Javascript & HTML & CSS2016. 12. 15. 21:49
미사일을 추가해서 동작은 잘 되는데, 설계가 형편없다.
머리로는 객체지향이 뭔지 아는데, 정작 설계에 반영하는 건 쉽지가 않다.
일단은 짜고 리팩토링 하면서 생각해 봐야겠다.
대충 초안이 나오면 네트워크 기능을 추가해 볼 계획..
<!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;border-radius:5px}
</style>
<script>//classes
function Bullet(type){
this.speed = 10;
this.type = type;
}
Bullet.prototype.shot = function(){
console.log("shot");
var bulletPosX = parseInt($("#hero").css("left")) + 20 + 'px';
var bulletPosY = parseInt($("#hero").css("top")) - 10 + 'px';
var bulletElement = "<div class='bullet' style='left:"+bulletPosX+";top:"+bulletPosY+"'></div>";
$("#stage").append(bulletElement);
}
</script>
<script>
var keyValue = {};
var bullet = {};
var bulletCnt = 0;
var controller = function(){
if(keyValue[37] == 'on' && parseInt($("#hero").css("left")) >= 5){
console.log("go left");
$("#hero").css("left", "-=5");
}
if(keyValue[38] == 'on' && parseInt($("#hero").css("top")) >= 5){
console.log("go up");
$("#hero").css("top", "-=5");
}
if(keyValue[39] == 'on' && parseInt($("#hero").css("left")) <= 445){
console.log("go right");
$("#hero").css("left", "+=5");
}
if(keyValue[40] == 'on' && parseInt($("#hero").css("top")) <= 445){
console.log("go bottom");
$("#hero").css("top", "+=5");
}
//bullet
if(keyValue[32] == 'on'){
console.log("space");
if(bulletCnt < 5){
bullet[bulletCnt] = new Bullet('normal');
bullet[bulletCnt++].shot();
}
keyValue[32] = undefined;
}
//bullet move
$(".bullet").css("top", "-=3");
//bullet destroy
console.log($(".bullet").css("top"));
if(parseInt($(".bullet").css("top")) < 0){
$(".bullet:first").remove();
bulletCnt--;
}
};
setInterval(controller, 10);
$(function(){
$(document).on("keydown", function(e){
keyValue[e.keyCode] = 'on';
if(e.keyCode==32){
keyValue[32] = 'on';
}
})
$(document).on("keyup", function(e){
keyValue[e.keyCode] = undefined;
})
})
</script>
</head>
<body>
<div id="stage">
<div id="hero"></div>
</div>
</body>
</html>
'Javascript & HTML & CSS' 카테고리의 다른 글
JSON 정렬 사이트 (0) | 2017.10.01 |
---|---|
파일업로드 하는 방법 (0) | 2016.12.31 |
javascript로 게임 만들기 - 부드러운 동작 (0) | 2016.12.15 |
Javascript로 게임 만들기(엉터리 코드) (0) | 2016.12.15 |
프론트엔드 연습용 템플릿 (0) | 2016.12.07 |