[英]How can I always move a ball at the same speed to an (x,y) position regardless of its starting position
当球靠近端点(橙色圆圈)时,它的移动非常慢,而离端点更远时,它的移动非常快。
发生这种情况的原因是因为我正在使用此代码来计算球的垂直和水平速度
var startingBallSpeed = 100;
xDistance = targetX - this.x;
yDistance = targetY - this.y;
this.horizontalVelocity = (xDistance / startingBallSpeed);
this.verticalVelocity = (yDistance / startingBallSpeed);
问题:如何确保球以相同的速度运动并且仍然会击中targetX和targetY
当前行为:靠近端点的球移动速度慢,远离端点的球移动速度快
期望的行为:球以相同的速度运动,而不管它们离终点有多近
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();
}
您需要对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
}
将您的球速调整到所需的恒定速度
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.