我创建了一个游戏的功能,子弹以恒定的速度飞向十字准线。但我有一个问题:怎样才能让子弹朝与射出方向相反的方向运动呢?
让我解释一下我想要做什么。当子弹接触到特定 Material 时,它会朝相反的方向移动。就像这张图片:
如您所见,子弹向相反的方向“弹跳”。
这是我的函数,如果您需要的话,我可以在其中设置子弹的线速度:
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 后可以取这些值进行反弹......
如图所示:
经过这次分析,我已经适应了一个简单的代码。
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/