如何将球以相同的速度移动到(x,y)位置,而不管其起始位置如何

时间:2016-05-14 08:50:14

标签: javascript jquery game-physics

此图片很好地说明了我的问题: http://i.imgur.com/2NdRXGn.gifv

当球接近其终点(橙色圆圈)时,球移动速度非常慢,但当球越远离其终点时,球的移动速度非常快。

发生这种情况的原因是因为我正在使用此代码来计算球的垂直和水平速度

var startingBallSpeed = 100;
xDistance = targetX - this.x;
yDistance = targetY - this.y;

this.horizontalVelocity = (xDistance / startingBallSpeed);
this.verticalVelocity = (yDistance / startingBallSpeed);

问题:我怎样才能确保球以相同的速度行进并仍然会击中目标X和目标

当前行为:靠近终点的球移动缓慢,远离终点的球快速移动
期望的行为:球以相同的速度移动,无论它们与端点的接近程度如何

JS:https://jsfiddle.net/7ct1ap53/1

ball1 = new Ball(400, 480, "green");
ball2 = new Ball(20, 480, "blue");

targetX = 500;
targetY = 400;
targetBall = new Ball(targetX, targetY, "magenta", radius=10)

var gameArea = {
  canvas: document.createElement("canvas"),
  start: function() {
    this.canvas.width = 500;
    this.canvas.height = 500;
    this.context = this.canvas.getContext("2d");
    document.body.insertBefore(this.canvas, document.body.childNodes[4]);
    this.interval = setInterval(updateGame, 20); //20
  }
};

function Ball(x, y, color, radius=15) {
  this.x = x;
  this.y = y;
  this.radius = radius;
  this.color = color

  this.draw = function() {
    gameArea.context.beginPath();
    gameArea.context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
    gameArea.context.fillStyle = color;
    gameArea.context.fill();
    gameArea.context.closePath();
  }

  this.launch = function() {
    var startingBallSpeed = 100;
    xDistance = targetX - this.x;
    yDistance = targetY - this.y;

    this.horizontalVelocity = (xDistance / startingBallSpeed);
    this.verticalVelocity = (yDistance / startingBallSpeed);
  }

  this.updatePos = function() {
    this.x += this.horizontalVelocity;
    this.y += this.verticalVelocity;
  };
}


$(function() {
  startGame();
});


function updateGame() {
    gameArea.context.clearRect(0,0,500,500);
    ball1.updatePos();
  ball2.updatePos();

  ball1.draw();
  ball2.draw();
  targetBall.draw();
}

function startGame() {

  gameArea.start();
  ball1.launch();
  ball2.launch();
}

1 个答案:

答案 0 :(得分:4)

你需要规范化由xDistance,yDistance定义的矢量来创建一个指定方向但长度为1的单位矢量。然后你可以将它乘以你想要的球速来获得速度。

通过除以长度归一化:

xDistance = targetX - this.x;
yDistance = targetY - this.y;
length = Math.sqrt((xDistance * xDistance) + (yDistance * yDistance));
if(length > 0) // avoid divide by zero
{
     xUnitVector = xDistance / length;
     yUnitVector = yDistance / length;

     this.horizontalVelocity = xUnitVector * startingBallSpeed;
     this.verticalVelocity = yUnitVector * startingBallSpeed;
}
else
{
     // cancel the launch because you are already at your destination
}

将球速调整到您需要的恒定速度