在画布边界弹跳的球

问题描述 投票:0回答:1
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var h = canvas.height;
var w = canvas.width;
var sAngle = 0;
var numB = 10; 
var speed = 50;
var dt = 0.01;
const PI = Math.PI;
function resetCanvas () {
  canvas.width = canvas.width;
};
function createBalls (){
for(var i = 1; i <= numB; i++){ 
if (i % 2 == 0) {
  window['ball' + i] = 
  {r:10, color:"white", x:w*Math.random(), y:h*Math.random(), v:speed}} else {
   window['ball' + i] = 
  {r:10, color:"white", x:w*Math.random(), y:h*Math.random(), v:-1 *speed}};
      }
    }
  createBalls();
function drawBalls () {
for (var i = 1; i <= numB; i++) {
ctx.beginPath();
ctx.arc(window['ball' + i].x, window['ball' + i].y, window['ball' + i].r, sAngle, 2*PI);
ctx.fillStyle = window['ball' + i].color;
ctx.fill();
ctx.strokeStyle = window['ball' + i].color;
ctx.stroke();
    }
}
drawBalls();
function moveBalls () {
for (var i = 1; i <= numB; i++) {
if (0 < window['ball' + i].x < w && 0 < window['ball' + i].y < h) 
{window['ball' + i].x = window['ball' + i].x + window['ball' + i].v * dt; 
window['ball' + i].y = window['ball' + i].y + window['ball' + i].v * dt}
if (window['ball' + i].x < 0 || window['ball' + i].x > w) 
{window['ball' + i].x = window['ball' + i].x + ((-1) * window['ball' + i].v * dt); 
window['ball' + i].y = window['ball' + i].y + window['ball' + i].v * dt}
if (window['ball' + i].y < 0 || window['ball' + i].y > h) 
{window['ball' + i].y = window['ball' + i].y + ((-1) * window['ball' + i].v * dt);
window['ball' + i].x = window['ball' + i].x + window['ball' + i].v * dt}
    }
}
function animate () {
resetCanvas();
drawBalls();
moveBalls();
};
setInterval(animate, 100 * dt);

我正在尝试使球以相反的方向从画布壁反弹;但是,现在他们只是碰到画布边框并滑到角落并消失了。关于如何改善moveBall函数中的if条件以使球从画布壁反弹的任何想法?

javascript bounce
1个回答
0
投票

不确定这是否是您唯一的问题,但是您的if陈述没有达到您的期望。例如:

if (0 < window["ball" + i].x < w && 0 < window["ball" + i].y < h)

这里您似乎想说0 < ball.x < w表示ball.x在零和屏幕宽度之间。问题在于这不是比较的工作方式。您需要说:

if (0 < window["ball" + i].x && window["ball" + i].x < w && 
    0 < window["ball" + i].y && window["ball" + i].y < h)

原因是表达式0 < x < w(0 < x) < w一样被执行,并且第一部分(0 < x)返回true(1)或false(0),并且两者都可能小于w,因此表达式始终为true

例如,尝试以下代码段:

let x = 7;
console.log("Nope:",x,"is bewteen 0 and 6:",0 < x < 6);
console.log("Yep! ",x,"is between 0 and 6:",0 < x && x < 6); 
© www.soinside.com 2019 - 2024. All rights reserved.