需要使球以击球的角度运动
need to make a ball travel in the angle it was hit from
self.hitBall = function(ball, x, y) {
var angle = Math.atan2((x - ball.centerX), (y - ball.centerY));
ball.velocityY = (Math.sin(angle) * 10);
ball.velocityX = (Math.cos(angle) * 10);
};
所以函数接收球,它有一个 centerX 变量和一个 centerY 变量。传递给函数的 x 和 y 是 x 和 y 是球被击中的点。我想让球沿着它被击中的方向移动。
不太确定为什么我的代码不起作用..它的行为很奇怪而且我不太擅长三角函数所以我不太确定为什么它不起作用。
您的代码有两个问题:
Math.atan2()
按 (y, x) 顺序获取参数。大多数语言(Java、JavaScript、C 等)都这样做(Microsoft Excel 和其他一些使用 (x, y) 顺序的语言除外)。
当您说“[使] 球以其被击中的角度行进”时,您想从球点中减去击中点。换句话说,向量是 (ball.centerX - hitX, ball.centerY - hitY).
因此,解决方案:
解决方案一:
var angle = Math.atan2((ball.centerY - y), (ball.centerX - x));
解决方案 2 - 进行不带角度的矢量数学运算(等效计算):
var dx = ball.centerX - x;
var dy = ball.centerY - y;
var norm = Math.sqrt(dx * dx + dy * dy);
ball.velocityX = (dx / norm) * 10;
ball.velocityY = (dy / norm) * 10;
self.hitBall = function(ball, x, y) {
var angle = Math.atan2((x - ball.centerX), (y - ball.centerY));
ball.velocityY = (Math.sin(angle) * 10);
ball.velocityX = (Math.cos(angle) * 10);
};
所以函数接收球,它有一个 centerX 变量和一个 centerY 变量。传递给函数的 x 和 y 是 x 和 y 是球被击中的点。我想让球沿着它被击中的方向移动。
不太确定为什么我的代码不起作用..它的行为很奇怪而且我不太擅长三角函数所以我不太确定为什么它不起作用。
您的代码有两个问题:
Math.atan2()
按 (y, x) 顺序获取参数。大多数语言(Java、JavaScript、C 等)都这样做(Microsoft Excel 和其他一些使用 (x, y) 顺序的语言除外)。当您说“[使] 球以其被击中的角度行进”时,您想从球点中减去击中点。换句话说,向量是 (ball.centerX - hitX, ball.centerY - hitY).
因此,解决方案:
解决方案一:
var angle = Math.atan2((ball.centerY - y), (ball.centerX - x));
解决方案 2 - 进行不带角度的矢量数学运算(等效计算):
var dx = ball.centerX - x; var dy = ball.centerY - y; var norm = Math.sqrt(dx * dx + dy * dy); ball.velocityX = (dx / norm) * 10; ball.velocityY = (dy / norm) * 10;