随机速度矢量公式不能正常工作

时间:2017-06-20 12:06:56

标签: javascript html math physics

我正在创建一个游戏,在开始时,球需要在html画布上随机进行,但所有方式都具有相同的速度。我正在使用这个公式:

phi = 2*Math.PI*Math.random();
vx = speed * Math.cos(phi);
vy = speed * Math.sin(phi);

但它并没有给我一个恒定的速度。有人能纠正这个公式吗?

以下是片段:



var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
setInterval(render, 10);
var ball = {
	x: 250,
    y: 250,
    vx: 5 * Math.cos(2 * Math.PI * Math.random()),
    vy: 5 * Math.sin(2 * Math.PI * Math.random()),
    r: 5
}
function render() {
	context.clearRect(0, 0, canvas.width, canvas.height);
	ball.x += ball.vx;
    ball.y += ball.vy;
	context.beginPath();
    context.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI);
    context.fillStyle = 'black';
    context.fill();
    context.stroke();
}

canvas {
    border: 1px solid;
}

<canvas id="canvas" width="500" height="500"></canvas>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

return new webpackDevServer(compiler, { contentBase: './dist', hot: true, publicPath: '/site/', proxy: { '/backend': { secure: false, target: 'http://localhost:8080/', pathRewrite: { '^/backend': '' } } } }).listen(80); 会在每次通话时返回新值。您需要将角度一次进行计算。

Math.random
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
setInterval(render, 10);
var phi = 2 * Math.PI * Math.random() // you need the same angle
// because sin^2(phi) + cos^2(phi) = 1
var ball = {
	x: 250,
    y: 250,
    vx: 5 * Math.cos(phi),
    vy: 5 * Math.sin(phi),
    r: 5
}
function render() {
	context.clearRect(0, 0, canvas.width, canvas.height);
	ball.x += ball.vx;
    ball.y += ball.vy;
	context.beginPath();
    context.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI);
    context.fillStyle = 'black';
    context.fill();
    context.stroke();
}
canvas {
    border: 1px solid;
}