javascript - 球相互反弹
问题描述
我正在处理这个脚本,其中我在画布上有 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);
解决方案
要互相弹起球,他是你需要知道的
球相撞了吗?确定的方法是测量两个圆的中心之间的距离。如果这小于组合半径,则球发生碰撞
碰撞后应该有什么方向?使用 atan2 计算两个球中心之间的角度。然后在那个角度上将它们设置在相反的方向上,这样它们就不会相互深入。当然,这个简单的解决方案忽略了球可能具有的现有动量。但是做动量计算(包括质量、速度和当前角度)要复杂得多。
推荐阅读
- python - 未找到 Spacy 更新 msvc
- html - 使用 CSS 网格将页脚置于视野之外
- java - Window操作创建的DataStream中的上下文时间戳
- javascript - 选项卡粘滞时转到另一个选项卡后不需要隐藏内容
- xml - CRM模块中的Many2one res.partner过滤器
- dictionary - 在 Flutter 中显示由 JSON 请求创建的标记的问题
- dart - 单击图标时,凸起的按钮大小发生了变化。如何解决这个问题?
- android - Xamarin HttpClient.PostAsync 死锁
- android - 在android中将联系人号码与firebase数据库电话号码进行比较时出错
- powershell - 在 PowerShell 中重命名文件名