Skip to content

Instantly share code, notes, and snippets.

@mizchi
Created October 11, 2009 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizchi/207498 to your computer and use it in GitHub Desktop.
Save mizchi/207498 to your computer and use it in GitHub Desktop.
//ウィンドウサイズ
const WIDTH=600;
const HEIGHT=450;
//canvas context
var ctx;
//キー入力
var key=[0,0,0,0,0]; // left, right, up, down
//スプライトのプロトタイプ
function Sprite(_x,_y){
this.x=_x;
this.y=_y;
};
window.onload = function init(){
cnt=0;//初期化
character=new Sprite(WIDTH/2,HEIGHT/2);//スプライトのインスタンス
ctx = document.getElementById('mainWindow').getContext('2d'); //描画するコンテキスト
if(ctx) setInterval(main,30); //コンテキストが取得できたならmain()関数を 繰り返し実行する
};
function main(){
update();
draw();
}
/* 一度描画したものは残りつづける為、毎回初期化する */
function draw(){
//画面の初期化
ctx.clearRect(0,0,WIDTH,HEIGHT);
ctx.save();
//ここにアニメーション
ctx.beginPath();
ctx.strokeStyle='rgb(0,0,0)';
ctx.arc(character.x,character.y,10,0, Math.PI*2 ,true);
ctx.stroke();
//空画面を復元
ctx.restore();
}
function update(){ //内部データの更新
if(key[0]) character.x-=3;
if(key[1]) character.x+=3;
if(key[2]) character.y-=3;
if(key[3]) character.y+=3;
}
function changeKey(which, to){
switch (which){
case 65:case 37: key[0]=to; break; // left
case 87: case 38: key[2]=to; break; // up
case 68: case 39: key[1]=to; break; // right
case 83: case 40: key[3]=to; break;// down
}
}
document.onkeydown=function(e){changeKey((e||window.event).keyCode, 1);};
document.onkeyup=function(e){changeKey((e||window.event).keyCode, 0);};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment