我正在学习Phaser的游戏编程,目前我正在构建一个简单的突破游戏。
当球击中球拍时,我使用以下代码来确定球的新x速度:
if (ball.x < paddle.x)
{
// Ball is on the left-hand side of the paddle
diff = paddle.x - ball.x;
ball.body.velocity.x = (-10 * diff);
}
else if (ball.x > paddle.x)
{
// Ball is on the right-hand side of the paddle
diff = ball.x -paddle.x;
ball.body.velocity.x = (10 * diff);
}
else
{
// Ball is perfectly in the middle
// Add a little random X to stop it bouncing straight up!
ball.body.velocity.x = 2 + Math.random() * 8;
}
这段代码最初是我从stackoverflow中得到的,虽然我不记得我害怕哪个帖子。 这样做的问题是,当球以一定角度向左或向右移动时,它在屏幕上看起来比直线向上更快。角度越明显,它出现的速度越快。
有谁知道如何解决这个问题?
此致 Crouz
答案 0 :(得分:0)
球的速度由水平(x
)速度和垂直(y
)速度的组合给出,由Pythagoras' theorem给出:
z 2 = x 2 + y 2
总体速度为z
。
如果您在不减少x
的情况下增加y
,则整体speed
也会增加。
如果您希望速度保持不变,则还需要调整y
。示例伪代码:
speed = sqrt(x^2 + y^2)
x = 2 + random()*8
y = sqrt(speed^2 - x^2)
您可以在进行任何调整之前计算speed
,然后再调整y
,将其合并到您的代码中:
// Calculate overall speed
var speed = Math.sqrt(
Math.pow(ball.body.velocity.x, 2) +
Math.pow(ball.body.velocity.y, 2)
);
if (ball.x < paddle.x)
{
// Ball is on the left-hand side of the paddle
diff = paddle.x - ball.x;
ball.body.velocity.x = (-10 * diff);
}
else if (ball.x > paddle.x)
{
// Ball is on the right-hand side of the paddle
diff = ball.x -paddle.x;
ball.body.velocity.x = (10 * diff);
}
else
{
// Ball is perfectly in the middle
// Add a little random X to stop it bouncing straight up!
ball.body.velocity.x = 2 + Math.random() * 8;
}
// Adjust y to maintain same overall speed
ball.body.velocity.y = Math.sqrt(
Math.pow(speed, 2) -
Math.pow(ball.body.velocity.x, 2)
);
这将始终产生正y
,因此您可能需要根据您希望它移动的方向(向上或向下)来否定它。