HTML5实现射击移动小球

<html>
<head>
<title>射击小球</title>
<script>
    var rad=8;
    var ctx;
    var vx;
    var posy;
    var vy=10;
    var a=2;
    var x;
    var y;
    var n=0;
    var evt;
    var targetx;
    var targety;
    var speed=5;
    var cishu=0;
    function init(){
        ctx=document.getElementById("canvas").getContext('2d');
        targetx=300;
        targety=300;
        ctx.lineWidth=5;
        ctx.strokeRect(0,0,400,400);
        ctx.fillStyle="rgb(0,255,0)";
        ctx.beginPath();
        ctx.arc(targetx,targety,rad,0,2*Math.PI,true);
        ctx.fill();
        
    }
    function fire(){
        cishu +=1;
        f.cishu.value=cishu;
        vx=Number(f.vx.value);
        posy=Number(f.posy.value);
        f.get.value=" ";
        x=5+rad;
        y=400-posy;
        evt=setInterval("moveBall();",50);
        return false;
    }
    function moveBall(){
        ctx.clearRect(0,0,400,400);
        //绘制标靶
        targetx=targetx+speed;
        if(targetx<100||targetx>350){
            speed *= -1;
        }
        ctx.fillStyle="rgb(0,255,0)";
        ctx.beginPath();
        ctx.arc(targetx,targety,rad,0,2*Math.PI,true);
        ctx.fill();
        //绘制炮弹
        n=n+0.5;
        x=x+vx;
        y=y+a*n;
        check();
        ctx.fillStyle="rgb(255,0,0)";
        ctx.beginPath();
        ctx.arc(x,y,rad,0,2*Math.PI,true);
        ctx.fill();
        ctx.strokeRect(0,0,400,400);
        
    }
    function check(){
        if((Math.abs(targetx-x)<2*rad-3)&&(Math.abs(targety-y)<2*rad-3)){
            clearInterval(evt);
            f.get.value="命中";
            n=0
        }
        if((x>400-rad)||(y>400-rad)){
            clearInterval(evt);
            f.get.value="未命中";
            n=0;
        }
    }
</script>    
</head>
<body οnlοad="init();">
<canvas id="canvas" width="400" height="400">
</canvas>
<form id='f' name='f' οnsubmit="return fire();">
    <div>
	水平速度 <input id='vx' name='vx' placeholder="水平速度" type="number" value="15">
	垂直高度 <input id='posy' name="posy" placeholder="垂直高度" type="number" value="385">
	</div>
    发射次数 <input id='cishu' name="cishu" value="0" readonly>
    <div>射击结果 <input id='get' name='get' value=' ' readonly></div>
    <input type="submit" value="发射">
</form>

</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值