我想沿着一条角度以度为单位的线将一个点平移到特定距离。
var initialPoint = [0,0]; //Starting Point
var distance = 100; //Distance in pixels to be translated
var degree = 45; //Direction of move
var translatedPoint = moveByDegree(initialPoint, degree, distance);
function moveByDegree(initialPoint, degree, distance)
{
//formula to generate translatedPoint by degree & distance
// . . .
return translatedPoint;
}
给我简单的算法或JavaScript代码。
你必须给出初始点,角度和移动单位。
Math.radians = function (degrees) {
return degrees * Math.PI / 180;
};
function move(point, angle, unit) {
const rad = Math.radians(angle % 360);
let [x, y] = point;
x += unit * Math.sin(rad);
y -= unit * Math.cos(rad);
return [x, y];
}
//////////////////
// demo:
const FPS = 60;
const jump = 3;
let angle = 135;
let point = [0, 0];
function animate () {
// calculate new point
point = move(point, angle, jump);
const [x, y] = point;
// update ball position
ball.style.left = x + 'px'
ball.style.top = y + 'px'
// continue animating while conditions fulfils
if( x >= 100 && y >= 100 )
angle = -45;
else if( x <= 0 && y <= 0 )
angle = 135;
setTimeout(animate, 1000/FPS);
}
animate();
b {
padding: 10px;
background: red;
position: absolute;
border-radius: 50%;
}
<b id='ball'></b>
输出看起来像
[1.2246467991473532e-14, 100]
- 这是由于浮点单元 (FPU) 算法的工作原理。