簡單的運動學,用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM