1

默认情况下,HTML 5 画布具有矩形形状,但如果我在画布下做任何动画,它将移动到矩形区域。

如果我将区域绑定到径向形状怎么办?它绝对不应该超出径向形状。

我们可以将边界限制为径向而不是默认的矩形吗?

您可以查看球超出径向边界 - http://jsfiddle.net/stackmanoz/T4WYH/

我现在设计了径向形状的边界,我也想限制径向区域。

球的限制区域-

function bounce() {
    if (x + dx > 293 || x + dx < 0) {
        dx = -dx;
    }
    if (y >= 290) {
        y = 290;
    }
    if (y + dy > 290 || y + dy < 0) {
        dx *= 0.99;
        dy = -dy;
    }
    if (Math.abs(dx) < 0.01) {
        dx = 0;
    }
    dy++;
}
4

3 回答 3

1

圆的笛卡尔公式是 (x − a) 2 + (y − b) 2 = r 2

所以在你的反弹条件下检查这个:

function bounce() {
    if( Math.pow(x - 150, 2) + Math.pow(y - 150, 2) > Math.pow(150, 2))
    {
        dx = -dx * (0.6 + (Math.random() * 0.8));
        dy = -dy * (0.6 + (Math.random() * 0.8));
    }
}

我正在使用随机弹跳,因为我无法使用入射速度和弹跳点的法线计算出正确的弹跳角度(我相信这里有人可以)

在这里更新小提琴:http: //jsfiddle.net/T4WYH/1/

于 2013-02-08T11:36:30.417 回答
0

几点,使用 requestAnimationFrame 而不是 setInterval

我会在画布中绘制大圆圈,而不是作为边框,然后您可以使用isPointInPath(x, y)来确定您的球是否在圆圈内(或任何其他任意路径

function draw() {
    ctx.clearRect(0, 0, 300, 300);
    ctx.beginPath()
    ctx.lineWidth = 1;
    ctx.strokeStyle = '#000';
    ctx.arc(150, 150, 150, 0, 2 * Math.PI, true);
    ctx.stroke();
    ctx.closePath();
    console.log(ctx.isPointInPath(x, y)); //Is (center) of ball in big circle
    ctx.beginPath();
    ctx.arc(x, y, 10, 0, 2 * Math.PI, true);
    ctx.closePath();
    ctx.fill();
    x += dx;
    y += dy;
    bounce();
}
于 2013-02-08T11:57:19.657 回答
0

我不想执行这个特定的任务,但你可以从这个网站获得如何从圈子反弹的想法:bbdizains.com

以及对应的功能:

move = function(){
 for (i=1; i<=3; i++) {
  A.x[i] = A.x[i] - A.v[i]*Math.sin(A.alfa[i]);
  A.y[i] = A.y[i] - A.v[i]*Math.cos(A.alfa[i]);
  x = A.x[i]-175;
  y = A.y[i]-233;
  x2 = x*x;
  y2 = y*y;
  if (x2+y2>=6561) {
    if (A.flag[i]==1) {
      gamma = Math.atan(y/x);    
      A.alfa[i] =  - 2*gamma - A.alfa[i];
      A.flag[i] = 0;
    }
  } else {
    A.flag[i] = 1;
  }                                                                   
  $('#r'+i).css('left',A.x[i]+'px');
  $('#r'+i).css('top',A.y[i]+'px'); 
  if ((Math.random()>0.95) && (x2+y2<6000)) {
    A.alfa[i] = A.alfa[i] + Math.PI*Math.random()*0.1;      
  }  
 }
}
于 2013-02-08T12:02:42.247 回答