java - 如何在libGDX中以相反的方式射击子弹

标签 java libgdx box2d velocity

我创建了一个游戏的功能,子弹以恒定的速度飞向十字准线。但我有一个问题:怎样才能让子弹朝与射出方向相反的方向运动呢?

让我解释一下我想要做什么。当子弹接触到特定 Material 时,它会朝相反的方向移动。就像这张图片:

enter image description here

如您所见,子弹向相反的方向“弹跳”。

这是我的函数,如果您需要的话,我可以在其中设置子弹的线速度:

public void direccion(float xx, float yy) {

        float mousex = Gdx.input.getX();
        float mousey = 0;
        if (shoot.getAngle() > 6.1 && shoot.getAngle() < 9.6) { 

            mousey = Gdx.input.getY() - 5;
        } else {
            mousey = Gdx.input.getY();
        }
        Vector3 mousePos = new Vector3(mousex, mousey, 0);
        jugador.camera.unproject(mousePos);
        float speed = 60f;
        float velx = mousePos.x - xx;
        float vely = mousePos.y - yy;
        float length = (float) Math.sqrt(velx * velx + vely * vely);
        if (length != 0) {
            velx = velx / length;
            vely = vely / length;
        }
        shoot.setLinearVelocity(velx * speed, vely * speed);

希望你能理解我的想法。谁能帮我解决这个问题吗?

最佳答案

在思考如何做到这一点之后,我有了一个想法。

根据 vector 数学,子弹在接触到有问题的 Material 后可以取这些值进行反弹......

如图所示:

enter image description here

经过这次分析,我已经适应了一个简单的代码。

        vectorPart = shoot.getLinearVelocity();
        if ((vectorPart.x > 0 && vectorPart.y < 0) || (vectorPart.x > 0 && vectorPart.y > 0)
                || (vectorPart.x < 0 && vectorPart.y < 0) || (vectorPart.x < 0 && vectorPart.y > 0)) {
            vectorPart = new Vector2(vectorPart.x, vectorPart.y * -1);
        } else {
            vectorPart = new Vector2(vectorPart.x * -1, vectorPart.y * -1);
        }
        shoot.setLinearVelocity(vectorPart.x, vectorPart.y);

我评估了 LinearVelocity vector ,然后修改了它的符号。

有了这个代码和anylisis,一切正常!

关于java - 如何在libGDX中以相反的方式射击子弹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57560948/

相关文章:

java - 如何使用正则表达式搜索字符串,并在找不到时返回空

java - 我怎样才能在UTC java中获得今天的具体时间

libgdx - Libgdx 中的视口(viewport)和相机之间的区别?

android - 如何开发Android游戏UI

java - Android 上的 LibGDX ClassNotFound

java - 在 google disk api 中使用凭据时出现问题

Java equals() 和 hashCode() 基于不同的字段?

java - 如何在 libgdx/box2d 中为特定主体强制执行最大速度?

c++ - 通过特定定制环绕世界边缘

iphone - Cocos2d CCSpirte runAction问题