java - 使用鼠标瞄准 LibGDX
问题描述
我在 libGDX 中制作游戏,但在设置 Bullet 类时遇到问题。我无法让弹丸进入鼠标位置。
我试图使用 Math.atan() 来找到我需要射击的角度,但我无法让它发挥作用。现在我只是使用距离来查找 x 和 y 轴上的速度。
private static final int SPEED = 500;
private static Texture texture;
String path = "C:\\Users\\minicodcraft\\Downloads\\game\\core\\assets\\";
private float x, y; // starting position
private float xVelocity, yVelocity;
private float yPos; // the y position of the mouse input
private float xPos; // the x position of the mouse input
public Bullet(float x, float y, float yPos, float xPos) {
this.x = x;
this.y = y;
this.xPos = xPos;
this.yPos = yPos;
this.xVelocity = 0f;
this.yVelocity = 0f;
calcDirection();
if (texture == null) {
texture = new Texture(path + "Bullet.png");
}
}
private void calcDirection() {
float xDistanceFromTarget = Math.abs(xPos - x);
float yDistanceFromTarget = Math.abs(yPos - y);
float totalDistanceFromTarget = xDistanceFromTarget + yDistanceFromTarget;
xVelocity = xDistanceFromTarget / totalDistanceFromTarget;
yVelocity = yDistanceFromTarget / totalDistanceFromTarget;
if (xPos < x) {
xVelocity *= -1;
}
if (yPos < y) {
yVelocity *= -1;
}
}
public void update(float deltaTime) {
if (x > 0 && y > 0) {
x += xVelocity * SPEED * deltaTime;
y += yVelocity * SPEED * deltaTime;
} else if (x < 0 && y > 0) {
x -= xVelocity * SPEED * deltaTime;
y += yVelocity * SPEED * deltaTime;
} else if (x > 0 && y < 0) {
x += xVelocity * SPEED * deltaTime;
y -= yVelocity * SPEED * deltaTime;
} else if (x < 0 && y < 0) {
x -= xVelocity * SPEED * deltaTime;
y -= yVelocity * SPEED * deltaTime;
}
}
public void render(SpriteBatch batch) {
batch.draw(texture, x, y);
}
解决方案
以下代码给出了从玩家位置到鼠标位置的速度:
float diffX = mouse.x - player.x;
float diffY = mouse.y - player.y;
float angle = (float) Math.atan2(diffY, diffX);
float velX = (float) (Math.cos(angle));
float velY = (float) (Math.sin(angle));
Vector2 velocity = new Vector2(velX, -velY);
velocity.nor();
velocity.scl(magnitudeSpeed);
velocity.scl(deltaTime);
然后velocity.x
是速度的 x 分量。分别为 y。无需再次乘以速度和 deltaTime,上面已经完成。
推荐阅读
- c++ - C++中的字符数组验证
- php - PHP 将重音字符导出到 XML 失败
- html - 轮播下一个/上一个按钮和滚动不起作用
- uwsgi - uwsgi 升级到 python3.7 以修复 ImportError: No module named 'encodings'
- java - 如何从类中获取变量的值?
- javascript - 数组对象值在js中没有计数
- react-native - React Native ScrollY Interpolate error 试图让帧超出范围索引 NaN
- postgresql - Postgres:`last_value` 澄清
- javascript - 如何将数组保存到会话存储?
- html - 显示问题
- div里面的元素