随机速度矢量公式无法正常工作
random velocity vector formula not working properly
我正在创建一个游戏,开始时,球需要在 html canvas 上随机移动,但所有方向的速度都相同。我正在使用这个公式:
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>
Math.random
returns 每次调用都有新值。您需要计算角度 ounce.
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;
}
<canvas id="canvas" width="500" height="500"></canvas>
我正在创建一个游戏,开始时,球需要在 html canvas 上随机移动,但所有方向的速度都相同。我正在使用这个公式:
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>
Math.random
returns 每次调用都有新值。您需要计算角度 ounce.
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;
}
<canvas id="canvas" width="500" height="500"></canvas>