首页 > 解决方案 > 球相互反弹

问题描述

我正在处理这个脚本,其中我在画布上有 x 个弹跳球(在本例中为 20 个球)。我的问题是,如何让它们在击中时相互反弹,以及在击中黄色矩形时反弹?

var mycanvas =document.getElementById("mycanvas");
var ctx=mycanvas.getContext("2d");
var w=500,h=500;

mycanvas.height=h;
mycanvas.width=w;

var ball=[];

function Ball(x,y,r,c,vx,vy){
  this.x=x; //starting x coordinate
  this.y=y; //starting x coordinate
  this.r=r; //radius  
  this.c=c; //color 
  this.vx=vx; // x direction speed
  this.vy=vy; // y direction speed
  this.update=function(){
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false);
        ctx.fillStyle = this.c;
        ctx.fill();
        ctx.closePath();
        this.x += this.vx;
        this.y += this.vy;
        //changing direction on hitting wall
        if(this.y>=(w-10)||this.y<=10){
        this.vy=-this.vy;
         }
        if(this.x>=(h-10)||this.x<=10){
        this.vx=-this.vx;
         }
}
}

function clearCanvas(){
ctx.clearRect(0, 0, w, h);
}

var count;
for (count = 0; count < 20; count++) {
  var rndColor=Math.floor((Math.random() * 9) + 1); //random color
    ball[count]= new Ball(Math.floor((Math.random() * 490) + 1),Math.floor((Math.random() * 490)+1),5,'red',5,5);
}

function update(){
  var i;
  clearCanvas();
    //draw rectangle 
    ctx.rect(250, 200, 10, 100);
    ctx.fillStyle = 'yellow';
    ctx.fill();

  for(i=0;i<count;i++){
        ball[i].update();
    }
}

setInterval(update, 1000/60);

标签: javascriptcanvashtml5-canvas

解决方案


要互相弹起球,他是你需要知道的

  1. 球相撞了吗?确定的方法是测量两个圆的中心之间的距离。如果这小于组合半径,则球发生碰撞

  2. 碰撞后应该有什么方向?使用 atan2 计算两个球中心之间的角度。然后在那个角度上将它们设置在相反的方向上,这样它们就不会相互深入。当然,这个简单的解决方案忽略了球可能具有的现有动量。但是做动量计算(包括质量、速度和当前角度)要复杂得多。


推荐阅读