我试图了解如何在动画中添加重力和风等物理原理。我无法完全围绕如何使球弹起来,好像它具有重力一样来回弹……每次更新时,我都会累积力,将其应用于速度,然后清除力。但是我能想到使其反弹的唯一方法是改变Y方向。但是然后它一直持续直到到达顶部。有什么明显的我想念的东西吗?任何建议表示赞赏。谢谢阅读

var C, canvas, context = null;
var gravity = {x:0, y:1};
var wind = {x:0.4, y:0};
var height = 140;
var width = 300;

function Ball(x,y,w,h) {
  var ball = this;
  this.x = x;
  this.y = y;
  this.w = w;
  this.h = h;
  this.xVelocity = 0;
  this.yVelocity = 0;
  this.xDirection = 1;
  this.yDirection = 1;

  this.update = function() {
  	ball.applyForce(gravity);
   	//ball.applyForce(wind);

    ball.x += (ball.xVelocity * ball.xDirection);
   	ball.y += (ball.yVelocity * ball.yDirection);

    if((ball.x + ball.w) >= width) {
    	//ball.xDirection = -1;
        ball.x = width - ball.w / 2 ;
        ball.xVelocity = -ball.xVelocity
    } else if(ball.x <= 0) {
    	//ball.xDirection = 1;
        ball.xVelocity = ball.xVelocity
    }

    if((ball.y + ball.h) >= height) {
    	//ball.yDirection = -1;
        ball.y = height - ball.w;
        ball.yVelocity = -ball.yVelocity
    } else if(ball.y <= 0) {
    	  //ball.yDirection = 1;
        ball.yVelocity = ball.yVelocity
    }

    //ball.clearForces();
  }

  this.draw = function() {
   context.beginPath();
   context.arc(ball.x,ball.y,ball.w,0,2*Math.PI);
   context.stroke();
  }

  this.applyForce = function(force) {
		ball.xVelocity += force.x;
 		ball.yVelocity += force.y;
  }

  this.clearForces = function(force) {
		ball.xVelocity = 0;
 		ball.yVelocity = 0;
  }
}

function Canvas( ) {
var CV = this;
var balls = new Array();
balls.push(new Ball(100, 10, 10, 10));

  this.loop = function() {
		CV.update();
		CV.draw();
    window.requestAnimationFrame(CV.loop);
  }

  this.update = function() {
  	for(var i=0; i<balls.length; i++) {
    	balls[i].update();
    }
  }

  this.draw = function() {
  	context.clearRect(0, 0, width, height);
  	for(var i=0; i<balls.length; i++) {
    	balls[i].draw();
    }
  }
}


canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
C = new Canvas( );
C.loop();
#canvas {border:1px solid #d4d4d4; }
<canvas id="canvas" width="300" height="140"></canvas>

最佳答案

在运动学中,简单的运动有时可以表示为v(t) = aΔt,其中vt秒的速度,而aΔt是加速度乘以Δt的间隔。

模拟此情况的一种方法可能是将ball.yVelocity组件计算为(-someAcceleration) * someTimeIndex或执行类似
var ball.yVelocity = ball.yVelocity - someFactor每个循环。

编辑1:我还将设置一个单独的变量,例如yVelocityAbs,以处理ball.yVelocity的大小,以免每次弹球时都弄乱方向。祝好运!

编辑2:尝试像这样更新clearForces()函数:

this.clearForces = function(force) {
         ball.xVelocity = 0;
        //ball.yVelocity = 0;
  }

它应该工作!尽管表现得相当呆板,但模拟效果更好。我建议添加一些功能来重设球。

10-01 01:02