本文介绍了球互相弹起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理此脚本,其中我在画布中有x编号的弹跳球(在这种情况下为20个球).我的问题是,如何使它们在撞击时相互反弹,以及在撞击时从黄色矩形处反弹?

I am working on this script where I have x-number bouncing balls (in this case 20 balls) in a canvas. My question is, how do I make them bounce off each other when they hit, as well as bounce off the yellow rectangle when they hit it?

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

推荐答案

要将球彼此弹开,他就是你需要知道的

To bounce balls off of one another, he's what you need to know

  1. 球碰到了吗?确定的方法是测量两个圆心之间的距离.如果这小于半径的总和,则说明球已发生碰撞

  1. Have the balls collided? The way to determine is to measure the distance between the centers of the two circles. If this is less than the combined radiuses, the balls have collided

碰撞后应该朝哪个方向前进?使用atan2计算两个球的中心之间的角度.然后以相反的角度将它们设置在该角度,以使它们彼此之间不会更深.当然,这种简单的解决方案忽略了球可能具有的现有动量.但是进行动量计算(涉及质量,速度和当前角度)更加复杂.

What direction should they have after colliding? Use use atan2 to calculate the angle between the centers of the two balls. Then set them in opposite directions on that angle, in a way that they don't end up deeper within each other. Of course, this simple solution ignores existing momentum that the balls may have. But doing the momentum calculation (which involves mass, speed, and current angle) is more complicated.

这篇关于球互相弹起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 02:23