게임/HTML 연습
CANVAS 연습14_2(배경 움직이기 && 키보드를 눌렀을 때 사람 움직임)
런던전통손만두
2018. 7. 1. 15:23
반응형
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CANVAS 연습</title>
<script src = "https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<canvas id="myCanvas" width="800" height="600" style="border: 1px dotted blue"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var bgImage = new Image();
bgImage.src = "https://t1.daumcdn.net/cfile/tistory/99664A3B5B35D3182C";
var userImage = new Image();
userImage.src = "https://t1.daumcdn.net/cfile/tistory/99EC173B5B386A8429";
var x = 0;
var speed = 5; //사람이 화면에서 움직일 속도
var keyCodeValue; //키보드 값 저장할 변수
function Background() { //배경 움직이는 부분
this.x = 0, this.y = 0, this.w = 2400, this.h = 600;
this.render = function() {
ctx.drawImage(bgImage, this.x-= 5, 0, 2400, 600);
if (this.x <= -1600) {
this.x = 0;
}
};
}
function Player() { //사람 그리기
this.x = 0, this.y = 0, this.w = 200, this.h = 200;
this.render = function () {
ctx.drawImage(userImage, this.x, this.y);
};
}
var background = new Background(); //배경 & 사람 객체 만들기
var player = new Player();
player.x = 30; //사람 좌표 설정
player.y = 150;
function updata() { //키보드를 누르면 비행기의 좌표값에 속도를 더해서 변경
if (keyCodeValue === "W") {
player.y -= speed;
} else if (keyCodeValue === "S") {
player.y += speed;
} else if (keyCodeValue === "A") {
player.x -= speed;
} else if (keyCodeValue === "D") {
player.x += speed;
}
}
function animate() { //배경, 사람 객체 그리기
background.render();
player.render();
updata();
}
var animateInterval = setInterval(animate, 30); //animate 함수를 30ms마다 실행
$(document).keydown(function(event) {
keyCodeValue = String.fromCharCode (event.keyCode); // event.keyCode값을 문자열로 변환하여 변수에 대입
});
$(document).keyup(function(event){
keyCodeValue=""; //변수의 내용 삭제
});
</script>
</body>
</html>
결과:
wasd키를 눌렀을 때 사람이 움직인다.
반응형