简单的运动学,用canvas写弹力球

  跟之前的随笔一样,因为本人仍是菜鸟一只,所以用到的技术比较简单,不适合大神观看。。。。。。

  学canvas学了有一个多礼拜了,觉得canvas真心好玩。学canvas的人想法估计都跟我差不多,抱着写游戏的态度去学canvas的。所以运动学啊、碰撞检测啊、一些简单的算法神马的是基础啊。以前没做过游戏的我学起来还真心吃力。今天就来说下用canvas写个最简单的弹力球游戏,就运用了最简单的重力作用以及碰撞检测。

  先上DEMO:弹力球DEMO (鼠标点击canvas里的空白区域会给与小球新速度)

  【创建小球对象】

  第一步就是先创建一个小球对象,写好小球的构造函数:

简单的运动学,用canvas写弹力球
var Ball = function(x , y , r , color){
            this.x = x;
            this.y = y;
            this.oldx = x;
            this.oldy = y;
            this.vx = 0;
            this.vy = 0;
            this.derection = true;
            this.radius = r;
            this.color = color;
        }
简单的运动学,用canvas写弹力球

 

  小球属性很简单,xy是小球的坐标,vx和vy是小球的初始水平速度和初始垂直速度。derection是小球的水平运动的方向,true是向右,false则是向左。radius就是小球的半径,color是小球颜色(为了区分不同球),oldx和oldy是记录小球的上一帧的位置,后期球与球之间碰撞后用于位置修正。

  小球属性写好后,就在小球原型中写小球的动作了:

简单的运动学,用canvas写弹力球
Ball.prototype = {
            paint:function(){
                ctx.save();
                ctx.beginPath();
                ctx.arc(this.x , this.y , this.radius , 0 , Math.PI*2);
                ctx.fillStyle=this.color;
                ctx.fill();
                ctx.restore();
            },
            run:function(t){
                this.oldx = this.x;
                this.oldy = this.y;

                if(this.derection){
                     this.vx = this.vx < 0 ? 0 : this.vx - mocali * t;
                 }
                 else {
                     this.vx = this.vx > 0 ? 0 : this.vx + mocali * t;
                 }
                 this.vy = this.vy + g * t;
                 this.x += t * this.vx * pxpm;
                 this.y += t * this.vy * pxpm;

                 if(this.y > canvas.height - ballRadius || this.y < ballRadius){
                     this.y = this.y < ballRadius ? ballRadius : (canvas.height - ballRadius);
                     this.vy = -this.vy*collarg
                 }
                 if(this.x > canvas.width - ballRadius || this.x < ballRadius){
                     this.x = this.x < ballRadius ? ballRadius : (canvas.width - ballRadius);
                     this.derection = !this.derection;
                     this.vx = -this.vx*collarg;
                 }

                 this.paint();
            },

        }
简单的运动学,用canvas写弹力球

 

  小球的动作方法也很简单,就两个,第一个方法是把自己画出来,第二个方法就是控制小球的运动。t是当前帧与上一帧的时间差。用于计算小球的速度的增量从而得出小球的位移增量,从而计算出小球的新位置并且将小球重绘。得出新位置的同时判断小球的新位置有无超出墙壁,如果超出则进行速度修正让小球反弹。

  第二个方法里的一些常量ballRadius =30, g = 9.8 , mocali = 0.5,balls = [],collarg = 0.8,pxpm = canvas.width/20; 意思很明显:ballradius是球半径,g是重力加速度,mocali是空气阻力引起的水平方向的减速度,balls是一个用于存放小球对象的数组,collarg是弹力系数。pxpm是像素与米之间的映射,把画布当成是20米宽的区域。

  【碰撞检测】

  创建好小球对象后,就开始写碰撞了,小球与小球之间的碰撞:

简单的运动学,用canvas写弹力球
function collision(){
            for(var i=0;i<balls.length;i++){
                for(var j=0;j<balls.length;j++){
                    var b1 = balls[i],b2 = balls[j];
                    if(b1 !== b2){
                        var rc = Math.sqrt(Math.pow(b1.x - b2.x , 2) + Math.pow(b1.y - b2.y , 2));
                        if(Math.ceil(rc) <= (b1.radius + b2.radius)){
                            var ax = ((b1.vx - b2.vx)*Math.pow((b1.x - b2.x) , 2) + (b1.vy - b2.vy)*(b1.x - b2.x)*(b1.y - b2.y))/Math.pow(rc , 2)
                            var ay = ((b1.vy - b2.vy)*Math.pow((b1.y - b2.y) , 2) + (b1.vx - b2.vx)*(b1.x - b2.x) + (b1.y - b2.y))/Math.pow(rc , 2)

                            b1.derection = (b1.vx - ax)*b1.vx < 0? !b1.derection : b1.derection;
                            b2.derection = (b2.vx + ax)*b2.vx < 0? !b2.derection : b2.derection;
                            b1.vx = (b1.vx-ax)*collarg;
                            b1.vy = (b1.vy-ay)*collarg;
                            b2.vx = (b2.vx+ax)*collarg;
                            b2.vy = (b2.vy+ay)*collarg;
                            
                            b1.x = b1.oldx;
                            b1.y = b1.oldy;
                            b2.x = b2.oldx;
                            b2.y = b2.oldy;
                        }
                    }
                }
            }
        }
简单的运动学,用canvas写弹力球

  每一帧都进行小球之间碰撞的判断,如果两个小球球心距离小于两球半径之和,则证明两个小球发生了碰撞。然后进行计算两个小球碰撞之后的速度变化量。ax和ay就是速度变化量。

  后面长长的公式就是这个:简单的运动学,用canvas写弹力球 , 具体原理我就不说了,想了解原理就直接戳 小球碰撞的算法设计 。 我只是用了其中一部分,没有做进一步细化了,小球位置修正就直接用碰撞后把上一帧的位置赋给小球来解决,所以多个小球碰撞时还是有bug的。。。。。毕竟不是专业做游戏的,算法什么的真心吃力啊。

  【运动动画】

  最后一步:

简单的运动学,用canvas写弹力球
canvas.onclick = function(event){
                event = event || window.event;
                var x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - canvas.offsetLeft;
                var y= event.clientY + document.body.scrollTop + document.documentElement.scrollTop - canvas.offsetTop;

                balls.forEach(function(){
                    this.vx = (x - this.x)/20; //初速度 m/s
                    this.vy = (y - this.y)/20;
                    this.derection = this.vx > 0 ? true : false;
                });
            }

            function animate(){
                ctx.save();
                ctx.fillStyle = "rgba(255,255,255,0.2)";
                ctx.fillRect(0,0,canvas.width,canvas.height)
                ctx.restore();
                // ctx.clearRect(0,0,canvas.width,canvas.height)

                 var t1 = new Date();
                 var t = (t1 - t0)/1000;
                 
                 balls.forEach(function(){
                     this.run(t);
                 });
                 collision();
                 t0 = t1;
                 
                 if("requestAnimationFrame" in window){
                    requestAnimationFrame(animate);
                }
                else if("webkitRequestAnimationFrame" in window){
                    webkitRequestAnimationFrame(animate);
                }
                else if("msRequestAnimationFrame" in window){
                    msRequestAnimationFrame(animate);
                }
                else if("mozRequestAnimationFrame" in window){
                    mozRequestAnimationFrame(animate);
                }
            }
简单的运动学,用canvas写弹力球

通过点击画布的位置来给于小球初速度,然后animate就是动画的每一帧运行的方法。上面的 ctx.fillStyle = "rgba(255,255,255,0.2)"; ctx.fillRect(0,0,canvas.width,canvas.height)是给小球添加虚影,我觉得这样会更好看,如果觉得不喜欢,就直接用clearRect清除就行了。然后就是计算每一帧的时间差,然后对小球数组里小球数组进行遍历重绘。然后再加入碰撞检测的collision方法。动画也就做完了。

  至此,就已经写完了,下面贴出全部代码:

简单的运动学,用canvas写弹力球
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <style>
        body{
            padding:0;
            margin:0;
            overflow: hidden;
        }
        #cas{
            display: block;
            border:1px solid;
            margin:50px auto;
        }
    </style>
    <script>
        onload = function(){
            canvas = document.getElementById("cas");
            ctx = canvas.getContext("2d");
            ballRadius =30, g = 9.8 , mocali = 0.5,balls = [],collarg = 0.8;
            pxpm = canvas.width/20;   //px/m

            for(var i=0;i<2;i++){
                var ball = new Ball(i*100 , canvas.height , ballRadius , "rgba("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+" , 1)");
                balls.push(ball);
            }

            var t0 = new Date();
            animate()

            canvas.onclick = function(event){
                event = event || window.event;
                var x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - canvas.offsetLeft;
                var y= event.clientY + document.body.scrollTop + document.documentElement.scrollTop - canvas.offsetTop;

                balls.forEach(function(){
                    this.vx = (x - this.x)/20; //初速度 m/s
                    this.vy = (y - this.y)/20;
                    this.derection = this.vx > 0 ? true : false;
                });
            }

            function animate(){
                ctx.save();
                ctx.fillStyle = "rgba(255,255,255,0.2)";
                ctx.fillRect(0,0,canvas.width,canvas.height)
                ctx.restore();
                // ctx.clearRect(0,0,canvas.width,canvas.height)

                 var t1 = new Date();
                 var t = (t1 - t0)/1000;
                 
                 balls.forEach(function(){
                     this.run(t);
                 });
                 collision();
                 t0 = t1;
                 
                 if("requestAnimationFrame" in window){
                    requestAnimationFrame(animate);
                }
                else if("webkitRequestAnimationFrame" in window){
                    webkitRequestAnimationFrame(animate);
                }
                else if("msRequestAnimationFrame" in window){
                    msRequestAnimationFrame(animate);
                }
                else if("mozRequestAnimationFrame" in window){
                    mozRequestAnimationFrame(animate);
                }
            }
        }

        function collision(){
            for(var i=0;i<balls.length;i++){
                for(var j=0;j<balls.length;j++){
                    var b1 = balls[i],b2 = balls[j];
                    if(b1 !== b2){
                        var rc = Math.sqrt(Math.pow(b1.x - b2.x , 2) + Math.pow(b1.y - b2.y , 2));
                        if(Math.ceil(rc) <= (b1.radius + b2.radius)){
                            console.log(rc)
                            var ax = ((b1.vx - b2.vx)*Math.pow((b1.x - b2.x) , 2) + (b1.vy - b2.vy)*(b1.x - b2.x)*(b1.y - b2.y))/Math.pow(rc , 2)
                            var ay = ((b1.vy - b2.vy)*Math.pow((b1.y - b2.y) , 2) + (b1.vx - b2.vx)*(b1.x - b2.x) + (b1.y - b2.y))/Math.pow(rc , 2)

                            b1.derection = (b1.vx - ax)*b1.vx < 0? !b1.derection : b1.derection;
                            b2.derection = (b2.vx + ax)*b2.vx < 0? !b2.derection : b2.derection;
                            b1.vx = (b1.vx-ax)*collarg;
                            b1.vy = (b1.vy-ay)*collarg;
                            b2.vx = (b2.vx+ax)*collarg;
                            b2.vy = (b2.vy+ay)*collarg;
                            // var cangle = Math.atan((b1.x-b2.x)/(b1.y-b2.y));
                            // var clength = ((b1.radius+b2.radius)-rc)/2;
                            // var cx = clength * Math.sin(cangle);
                            // var cy = clength * Math.cos(cangle);
                            // b1.x = b1.x+cx;
                            // b1.y = b1.y+cy;
                            // b2.x = b2.x-cx;
                            // b2.y = b2.y-cy;
                            b1.x = b1.oldx;
                            b1.y = b1.oldy;
                            b2.x = b2.oldx;
                            b2.y = b2.oldy;
                            console.log(Math.sqrt(Math.pow(b1.x - b2.x , 2) + Math.pow(b1.y - b2.y , 2)))
                        }
                    }
                }
            }
        }

        Array.prototype.forEach = function(callback){
            for(var i=0;i<this.length;i++){
                callback.call(this[i]);
            }
        }

        var Ball = function(x , y , r , color){
            this.x = x;
            this.y = y;
            this.oldx = x;
            this.oldy = y;
            this.vx = 0;
            this.vy = 0;
            this.derection = true;
            this.radius = r;
            this.color = color;
        }

        Ball.prototype = {
            paint:function(){
                ctx.save();
                ctx.beginPath();
                ctx.arc(this.x , this.y , this.radius , 0 , Math.PI*2);
                ctx.fillStyle=this.color;
                ctx.fill();
                ctx.restore();
            },
            run:function(t){
                this.oldx = this.x;
                this.oldy = this.y;

                if(this.derection){
                     this.vx = this.vx < 0 ? 0 : this.vx - mocali * t;
                 }
                 else {
                     this.vx = this.vx > 0 ? 0 : this.vx + mocali * t;
                 }
                 this.vy = this.vy + g * t;
                 this.x += t * this.vx * pxpm;
                 this.y += t * this.vy * pxpm;

                 if(this.y > canvas.height - ballRadius || this.y < ballRadius){
                     this.y = this.y < ballRadius ? ballRadius : (canvas.height - ballRadius);
                     this.vy = -this.vy*collarg
                 }
                 if(this.x > canvas.width - ballRadius || this.x < ballRadius){
                     this.x = this.x < ballRadius ? ballRadius : (canvas.width - ballRadius);
                     this.derection = !this.derection;
                     this.vx = -this.vx*collarg;
                 }

                 this.paint();
            },

        }

    </script>
    <title>Document</title>
</head>
<body>
    <div >
        <canvas id=‘cas‘ width="1200" height="600">浏览器不支持canvas</canvas>
    </div>
</body>
</html>
View Code

  再坚持十八天就可以放假回家了。。。。加油。。。。

  

简单的运动学,用canvas写弹力球

上一篇:进程关系之会话


下一篇:短视频APP开发,前辈告诫我一定要选择开源源码