ねっとぱんだ-プログラミング勉強ブログ-

Webデザイン、プログラミングの勉強ブログ。

【javascript】キャラクターを操作して動かすアニメーション


これが歩きます。
panda
関数をまとめるところは今後やっていきます。。。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<style>
#img{
    position:absolute;
    z-index:-999;
    top:100px;
    left:100px;
}
.controlar{
    position:static;
    z-index:999;
    width:100px;
    height:100px;
    text-align:center;
}
.controlar span{
    cursor: pointer;
}
</style>
</head>
<body>
<div class="controlar">
<span id="up"></span>
<div class="wrapper">
<span id="left"></span>
<span id="stop"></span>
<span id="right"></span>
</div><!--/.wrapper-->
<span id="down"></span>
</div>
<p>
<img id="img" src="img/10.jpg" alt="pnd">
</p>
<script>
var up = document.getElementById('up');
var left = document.getElementById('left');
var right = document.getElementById('right');
var down = document.getElementById('down');
var img = document.getElementById('img');
var stop = document.getElementById('stop');
var idx = 0;
var tid = null;
var x = 100;
var y = 100;
var dx = 20;
var dy = 20;
var speed = 200;
up.addEventListener('click',timer_up,false);
left.addEventListener('click',click_left,false);
right.addEventListener('click',click_right,false);
down.addEventListener('click',click_down,false);
stop.addEventListener('click',click_stop,false);
function timer_up(){
    click_stop();
    idx++;
    idx %= 4;
    img.src = 'img/4'+ idx + '.jpg';
    tid = setTimeout(timer_up,speed );
    console.log(y);
    if(y > -60){
    y -= dy;
    img.style.top = y + 'px';
    }
}
function timer_left(){
    click_stop();
    idx++;
    idx %= 4;
    img.src = 'img/3'+ idx + '.jpg';
    tid = setTimeout(timer_left,speed );
    if(x > -60){
    x -= dx;
    img.style.left = x + 'px';
    console.log(x);
    }
}
function timer_right(){
    click_stop();
    idx++;
    idx %= 4;
    img.src = 'img/2'+ idx + '.jpg';
    tid = setTimeout(timer_right,speed);
    if(x < (screen.width / 2) - 100){
    x += dx;
    img.style.left = x + 'px';
    console.log(x);
    }
}
function timer_down(){
    click_stop();
    idx++;
    idx %= 4;
    img.src = 'img/1'+ idx + '.jpg';
    tid = setTimeout(timer_down,speed);
    if(y < (screen.height / 2) - 100){
    y += dy;
    img.style.top = y + 'px';
    console.log(y);
    }
}
function click_stop(){
    clearTimeout(tid);
    tid = null;
}
function click_up(){
        timer_up();
}
function click_left(){
        timer_left();
}
function click_right(){
        timer_right();
}
function click_down(){
        timer_down();
}
</script>
</body>
</html>