两个物体之间的角度

时间:2018-04-11 08:54:28

标签: java game-maker

在名为Game Maker Studio的游戏引擎中,有一个名为point_angle(x1, y1, x2, y2)的函数。 https://docs.yoyogames.com/source/dadiospice/002_reference/maths/vector%20functions/point_direction.html

此函数返回2个对象之间的角度(参见图像)。我如何在java中重新创建这个函数?

此外,在找到角度后,我有这个课程:

int velX = 0, velY = 0;

public void tick() {
    x += velX;
    y += velY;
}

tick()方法与此游戏循环一起运行(如果重要的话):

long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int updates = 0;
int frames = 0;
while(running){
    long now = System.nanoTime();
    delta += (now - lastTime) / ns;
    lastTime = now;
    while(delta >= 1){
        tick();
        updates++;
        delta--;
    }
    render();
    frames++;

    if(System.currentTimeMillis() - timer > 1000){
        timer += 1000;
        System.out.println("FPS: " + frames + " TICKS: " + updates);
        frames = 0;
        updates = 0;
    }
}

如何修改velXvelY,以便在Game Maker Studio中复制函数point_direction(x1, y1, x2, y2)

感谢您的时间。

PS:我正在尝试重新创建上面链接中显示的示例代码

1 个答案:

答案 0 :(得分:0)

实现角度功能实际上非常简单。使用函数Math.atan2(y, x),您可以获得从x轴到坐标的角度。

Angle from x-axis to point

此计算仅适用于相对于原点的一个点。因此,在进行角度计算之前,我们需要将第二个对象坐标转换为相对于原点。

enter image description here

以下是一些伪代码示例:

function angle(point1, point2) {
    translatedPoint = point2 - point1
    angle = atan2(translatedPoint.y, translatedPoint.x)
    return angle
}

此结果将以弧度为单位,因此如果您需要度数,则必须将其转换为该度数。

这比您的用例更复杂。您没有使用角度来表示您的动作。最简单的方法是只取第二个点减去第一个点,然后得到一个从第一个点到第二个点的向量。如果你对这个向量进行标准化(使长度为1),你将获得从第一个点到第二个点的方向。

function dirTo(x1, y1, x2, y2) {

    newX = x2 - x1
    newY = y2 - y1

    // normalize the vector
    dirX = newX / sqrt(newX * newX + newY * newY)
    dirY = newY / sqrt(newX * newX + newY * newY)

    return (dirX, dirY)
}

方向向量现在可以乘以一些标量(在你的情况下是速度),你有velXvelY

相关问题