Html/Javascript 做游戏的第一步: 2球碰撞游戏(附全部代码)

本来一心一意学Python, 结果在做爬虫的时候,发现如果不懂Html/Javascript 的话, 很难做好。 好吧, Html/Javascript 确实很枯燥, 只好先做个小游戏: 2 球动态碰撞, 碰撞后自动分开。这样, 学习起来应该更有趣一些。

代码如下:

<!DOCTYPE html>
<html>
    
<body>
<canvas id="myCanvas" width="300" height="280"></canvas>

<script>

var ctx = document.getElementById('myCanvas').getContext('2d');
var lastframe = 0;
 
var Box={x:1,y:1,width:myCanvas.width-2,height:myCanvas.height-2}; 

class Ball {
    constructor(x,y,r,speed) {
        this.x=x;
        this.y=y;
        this.r=r;
        this.xdir=1;
        this.ydir=1;
        this.speed=speed;
        }
    update(dt) {
        this.x+=dt*this.speed*this.xdir;
        this.y+=dt*this.speed*this.ydir;
        if (this.y+this.r> Box.height+Box.y){
            this.ydir=-1;}
        if (this.x+this.r>Box.width+Box.x) {
            this.xdir=-1;}
        if (this.y-this.r< Box.y){
            this.ydir=1;}
        if (this.x-this.r<Box.x) {
            this.xdir=1;}        
        
        }
    }
     
const ball1=new Ball(12,23,20,200);
const ball2=new Ball(150,210,35,150);

function collide(b1,b2) {
    dist=Math.sqrt((b1.y-b2.y)*(b1.y-b2.y)+(b1.x-b2.x)*(b1.x-b2.x));
    if (dist<b1.r+b2.r) return 1; 
    return 0;}

function main(tframe) {
        // Request animation frames
        window.requestAnimationFrame(main);
        //document.write(tframe)
        // Update and render the game
        update(tframe);
        render();
    }

function update(tframe) {
        var dt = (tframe - lastframe)/1000;
        lastframe = tframe;
        
        ball1.update(dt);
        ball2.update(dt);
        if (collide(ball1,ball2)) { 
            temp=ball1.xdir;
            ball1.xdir=ball2.xdir;
            ball2.xdir=temp;
            temp=ball1.ydir;
            ball1.ydir=ball2.ydir;
            ball2.ydir=temp; } 
    }        
            
function draw_ball(b) {
    ctx.fillStyle = "#f00";
    ctx.beginPath();
    ctx.arc(b.x,b.y,b.r,0,2*Math.PI,1);
    ctx.fill();
  }
    
function drawFrame() {
        // Draw background and a border
        ctx.fillStyle = "#d0d0d0";
        ctx.fillRect(0, 0, myCanvas.width, myCanvas.height);
        
        ctx.strokeStyle="#000000";
        ctx.lineWidth=2;
        ctx.strokeRect(Box.x,Box.y,Box.width,Box.height);
    }

function render() {
    drawFrame();
    draw_ball(ball1);
    draw_ball(ball2);
}

main(0);

</script>

</body>
</html>

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>