繁体   English   中英

Java游戏,弹跳与动作

[英]Java Game, Bouncing & Movements

我正在尝试创建一个简单的游戏库,主要是用来教自己。 我在这里和网上都读过一些帖子。 但是我认为我的问题有所不同,因为我使用的是“自己的逻辑”。

基础:

我在屏幕上的所有对象都称为“实体”,并且它们能够实现称为“ EntityActionListener”的接口,该接口允许与鼠标,键盘交互,在屏幕上移动等。

如何最好地移动实体?

理念:

首先,我要实现运动,然后是实体的弹跳,然后是碰撞。

对于运动和弹跳,这是我遇到的问题,我需要以下变量和函数:

protected float posx = 0, posy = 0;
protected float v = 0, vx = 0, vy = 0;
protected int direction = 0;

我使用setVelocity(float arg1)函数将速度(v)设置为arg1并更新轴(vx,vy)上的速度:

/**
 * Set the velocity on both axis according to the direction given
 *
 * @param arg1 the direction in degrees
 * @param arg2 the velocity
 */
private void setVelocityOnAxis(int arg1, float arg2)
{
    // Check for speed set to 0
    if (arg2 == 0) {
        vx = 0;
        vy = 0;
        return;
    }

    // Set velocity on axis
    vx = (float) (Math.cos(arg1 * Math.PI / 180) * arg2);
    vy = (float) (Math.sin(arg1 * Math.PI / 180) * arg2);
}

因此,速度(v)可能会在触发事件中更新。 =>此步骤似乎正常。

但是我在应按以下方式处理的方向上遇到麻烦:

/**
 * Set the entity direction
 *
 * @param arg1 the direction in degrees
 */
protected final void setDir(int arg1)
{
    // Update direction
    direction = arg1;

    // Update velocity on axis
    setVelocityOnAxis(direction, v);
}

/**
 * Get the enity direction based on the axis
 *
 * @param arg1 the x velocity
 * @param arg2 the y velocity
 */
protected final int getPointDir(float arg1, float arg2)
{
    // Set the direction based on the axis
    return (int) (360 - Math.abs(Math.toDegrees(Math.atan2(arg1, arg2)) % 360));
}

我想在边框上弹跳,因此我通过比较x和y坐标检查了4个方向,并根据侧面将vx或vy设置为其加法逆数(例如1到-1)。 但这确实失败了。

如果我只更新两侧的vx或vy,它会像预期的那样反弹,但是由于这个原因,方向没有更新。

这是我使用的代码:

// ...
// Hit bounds on x axis
direction = -vx; // works.
setDir(getPointDir(-vx, vy)); // does not work.

我在几何和三角学上不是那么好。 问题是我不能说为什么在360方向上水平速度为1的碰撞导致45度或我从调试打印中得到的其他奇怪的东西...

我真的希望有人能帮助我。 我只是无法解决。

编辑:

我的问题是:为什么这不起作用。 setDir()或getPointDir()中的某些代码一定是错误的。

编辑2

所以,我终于开始工作了。 问题是实体的方向为45,并且向下而不是向上移动,因此我对v速度加了反比-这会导致此愚蠢的错误,因为负号和负号为正,而当我弹跳时,它总是同时改变两个速度,即vx和vy。 我只需要更改度数的计算即可。 谢谢您的帮助。

我猜测getPointDir()setVelocity()应该分别从x,y和度数方向计算以度为单位的方向。 在这种情况下,这是getPointDir()的正确行:

return (int) (360 + Math.toDegrees(Math.atan2(arg2, arg1))) % 360;

一个简单的测试:

public static void main(String[] args) {
    Test t = new Test();

    for (int i = 0; i < 360; i++) {
        t.setVelocityOnAxis(i, 10);
        System.out.println("Angle: " + i + " vx: " + t.vx + " vy: " + t.vy);
        System.out.println("getPointDir: " + t.getPointDir(t.vx, t.vy));
    }

}

根据错误进行编辑atan2()始终为y,x -更易于发现除arg1,arg2以外的变量名称。 另一个错误是在Math.abs逻辑中。

检查此答案 轴上有正确的跳动。 您必须考虑入射角与出口角一样大,正好相反。 帖子中的图片对此进行了描述。 祝好运。

也许这就是您要寻找的东西...(仍然不确定我是否得到您的代码)。

getPointDir()

double deg = Math.toDegrees(Math.atan2(arg1, arg2));
if (deg < 0) deg += 360;
return (int) deg;

然后像原始帖子一样使用setDir(getPointDir(-vx, vy))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM