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

jos*_*ron 3 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;
}
Run Code Online (Sandbox Code Playgroud)

我已经取出cx运动只是为了上/下动画和圆形绘制代码的空间下一步将是什么?

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

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

Sho*_*omz 20

您非常接近,将重力视为恒定的向下速度增量,因此在每个步骤中您都需要将其添加到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();
}
Run Code Online (Sandbox Code Playgroud)
canvas {border: 1px solid black; cursor: crosshair;}
p {margin: 0;}
Run Code Online (Sandbox Code Playgroud)
<canvas id="gameCanvas"></canvas>
<p>Throw the ball by holding and releasing the left mouse button on the canvas (reverse slingshot)</p>
Run Code Online (Sandbox Code Playgroud)