如何在javascript中将重力应用于弹跳球 -

时间:2015-05-01 05:50:48

标签: javascript canvas

我希望从一个球在画布周围来回反弹到有一些重力并最终掉落。 我知道我需要在达到底部时改变速度,但我不知道应该如何进行和编码。

我是一名全新的JS学生,没有物理背景 - 这有多难?我很高兴学习等等。我试过让球碰撞并以正确的角度脱落,但现在看来我已经高高在上了。

var canvas,
    ctx,
    cx = 100,
    cy = 150,
    vx = 0,
    vy = 5,
    radius = 30;

function init() {

    canvas = document.getElementById("gameCanvas");
    ctx = canvas.getContext("2d");

    circle();
}

function circle() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    requestAnimationFrame(circle);

    if (cx + radius > canvas.width || cx - radius < 0)
    vx = -vx;
    if (cy + radius > canvas.height || cy - radius < 0)
    vy = -vy;

    cx += vx;  
    cy += vy;
}

我只是为了上/下动画而取出cx动作,而圆圈则为空间绘制代码 下一步会是什么?

我会将其当前速度乘以碰撞时的数字0.8,以及在何处/如何?

原谅基本性/可怕的书面代码 - 必须从某处开始!

1 个答案:

答案 0 :(得分:18)

你非常接近,认为引力是一个恒定的向下速度增量,因此在每一步中你需要将它添加到你的vy计算中。

  

“我知道我需要在到达底部时改变速度”

这不是真的,因为重力一直影响着物体。触摸底部时,会发生材料阻尼和表面摩擦等现象。

var canvas,
  ctx,
  cx = 100,
  cy = 100,
  vx = 2,
  vy = 5,
  radius = 5,
  gravity = 0.2,
  damping = 0.9,
  traction = 0.8,
  paused = false;
  ;

function init() {

  canvas = document.getElementById("gameCanvas");
  ctx = canvas.getContext("2d");
  
  canvas.width = 300;
  canvas.height = 150;

  circle();
}

function circle() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  if (!paused)
    requestAnimationFrame(circle);

  if (cx + radius >= canvas.width) {
    vx = -vx * damping;
    cx = canvas.width - radius;
  } else if (cx - radius <= 0) {
    vx = -vx * damping;
    cx = radius;
  }
  if (cy + radius >= canvas.height) {
    vy = -vy * damping;
    cy = canvas.height - radius;
    // traction here
    vx *= traction;
  } else if (cy - radius <= 0) {
    vy = -vy * damping;
    cy = radius;
  }

  vy += gravity; // <--- this is it

  cx += vx;
  cy += vy;

  ctx.beginPath();
  ctx.arc(cx, cy, radius, 0, 2 * Math.PI, false);
  ctx.fillStyle = 'green';
  ctx.fill();
}

init();

// fancy/irrelevant mouse grab'n'throw stuff below
canvas.addEventListener('mousedown', handleMouseDown);
canvas.addEventListener('mouseup', handleMouseUp);

function handleMouseDown(e) {
  cx = e.pageX - canvas.offsetLeft;
  cy = e.pageY - canvas.offsetTop;
  vx = vy = 0;
  paused = true;
}

function handleMouseUp(e) {
  vx = e.pageX - canvas.offsetLeft - cx;
  vy = e.pageY - canvas.offsetTop - cy;
  paused = false;
  circle();
}
canvas {border: 1px solid black; cursor: crosshair;}
p {margin: 0;}
<canvas id="gameCanvas"></canvas>
<p>Throw the ball by holding and releasing the left mouse button on the canvas (reverse slingshot)</p>