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

  声明:本文为原创文章,如需转载,请注明来源WAxes,谢谢!

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

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

  先上DEMO:弹力球DEMO (鼠标点击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.radius = r;
            this.color = color;
        }

 

  小球属性很简单,xy是小球的坐标,vx和vy是小球的初始水平速度和初始垂直速度。radius就是小球的半径,color是小球颜色(为了区分不同球),oldx和oldy是记录小球的上一帧的位置,后期球与球之间碰撞后用于位置修正(后面其实没用上,位置修正直接计算了,如果用oldx来设置很不严谨,不过记录一下,难免会用得到)。

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

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();
                this.moving = false;
            },
            run:function(t){
                if(!this.candrod) {
                    this.paint();
                    return};
                this.oldx = this.x;
                this.oldy = this.y;

                
                 if(Math.abs(this.vx) < 0.01){
                     this.vx = 0;
                 }
                 else this.vx += this.vx>0? -mocali*t : 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.derectionX = !this.derectionX;
                     this.vx = -this.vx*collarg;
                 }
                 this.paint();
            },

        }

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

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

  【碰撞检测】

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

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.vx = (b1.vx-ax)*collarg;
                            b1.vy = (b1.vy-ay)*collarg;
                            b2.vx = (b2.vx+ax)*collarg;
                            b2.vy = (b2.vy+ay)*collarg;

                            //获取两球斜切位置并且强制扭转
                            var clength = ((b1.radius+b2.radius)-rc)/2;
                            var cx = clength * (b1.x-b2.x)/rc;
                            var cy = clength * (b1.y-b2.y)/rc;
                            b1.x = b1.x+cx;
                            b1.y = b1.y+cy;
                            b2.x = b2.x-cx;
                            b2.y = b2.y-cy;
                        }
                    }
                }
            }
        }

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

  后面长长的公式就是这个: ,具体原理我就不说了,想了解原理就直接戳 小球碰撞的算法设计 。 下面那段就是防止小球重复碰撞检测导致无法正常反弹,所以计算两小球的球心距离,然后算出两个小球的斜切位置,并且将两个小球的位置进行更正。

  【运动动画】

  最后一步:

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;
                });
            }

            

            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;
                 collision();
                 balls.forEach(function(){
                     this.run(t);
                 });
                 
                 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);
                }
            }
        }

 

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

  至此,就已经写完了,源码地址:

  https://github.com/whxaxes/canvas-test/blob/gh-pages/src/Other-demo/shotBall.html

转载于:https://www.cnblogs.com/axes/p/3513343.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值