<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>
HTML5实现射击移动小球
最新推荐文章于 2023-11-09 14:23:03 发布