计算轨道运行物体的位置

aki*_*uri 2 javascript animation trigonometry

我正在使用画布创建太阳系动画,并且在计算对象的位置(x,y)值时出现问题.

地球围绕太阳旋转,我需要计算并更新地球在每一帧的位置.利用地球的位置,我将围绕地球围绕月球运行.

相关功能是这样的:

orbitAround : function (master) {
    master.makeOrbitCenter();
    this.increaseOrbitAngle();
    context.rotate(this.orbit.angle * Math.PI/180);
    context.translate(this.orbit.distance, 0);

    // calculate and update the X and Y position of the earth
    // so that luna can orbit around earth
    // these are the initial values of earth
    this.position.x = master.position.x + this.orbit.distance;
    this.position.y = master.position.y;
},
Run Code Online (Sandbox Code Playgroud)

小提琴演示

为了简单起见,我画了这张照片

在此输入图像描述

让我们说蓝色圆盘是地球,位于(300,200).太阳位于(200,200),它们之间的距离为100.在地球围绕太阳旋转45度之后,它的位置是什么?如何使用给定值计算它?

she*_*nan 5

看起来你在那里工作了,但这里有一个细分:

Math.cos并沿轴Math.sin返回理论xy位置.它们需要以弧度给出角度.

因此,为了获得45度角的位置,您基本上需要首先计算度数的弧度.

var degrees = 45;
var radians = degrees * (Math.PI / 180);
Run Code Online (Sandbox Code Playgroud)

结果,这是0.785398163.然后,您可以使用以下方法获取轨道对象的坐标xy坐标:

var x = Math.cos(0.785398163) * distance;
var y = Math.sin(0.785398163) * distance;
Run Code Online (Sandbox Code Playgroud)

单帧的整个过程如下所示:

var distance = 100; // from the centre of orbit
var degrees = 45; // around a 360 degree orbit
var radians = degrees * (Math.PI / 180);

var x = Math.cos(radians) * distance;
var y = Math.sin(radians) * distance;
Run Code Online (Sandbox Code Playgroud)

这是一个非常基本的方形行星和一切的小提琴.