在 Java/Slick2D 中向鼠标位置射击子弹
Shooting bullet towards mouse position in Java/Slick2D
我正在尝试实现一种向鼠标位置发射子弹的方法。我不知道它的数学或逻辑。这是一款 2D 俯视游戏。我让子弹向右发射并在某一点结束。我需要知道向鼠标位置开火的逻辑,而不是仅仅向 x 位置加 1。
使用atan2求出子弹原点与鼠标光标的夹角。然后使用 Sin 和 Cos 计算子弹的 x 和 y 速度。
伪代码
public void ShootBullet()
{
double bulletVelocity = 1.0; //however fast you want your bullet to travel
//mouseX/Y = current x/y location of the mouse
//originX/Y = x/y location of where the bullet is being shot from
double angle = Math.Atan2(mouseX - originX, mouseY - originY);
double xVelocity = (bulletVelocity) * Math.Cos(angle);
double yVelocity = (bulletVelocity) * Math.Sin(angle);
}
这是我生成射弹的代码。
public void spawnProjectile(Input input) {
double mouseX = 0;
double mouseY = 0;
double xVel;
double yVel;
double angle;
if (timer > 0) {
timer--;
}
if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
mouseX = input.getMouseX();
mouseY = input.getMouseY();
if (projectiles.size() < 1 && timer <= 0) {
projectiles.add(new Projectile((int) x + 8, (int) y + 8, 8, 8));
}
}
if (projectiles.size() > 0) {
for (int i = 0; i < projectiles.size(); i++) {
projectiles.get(i).update(input);
double originX = x;
double originY = y;
angle = Math.atan2(mouseX - originX, mouseY - originY);
xVel = (bulletVel) * Math.cos(angle);
yVel = (bulletVel) * Math.sin(angle);
projectiles.get(i).x += xVel;
projectiles.get(i).y += yVel;
if (projectiles.get(i).timer == 0) {
projectiles.remove();
}
}
}
}
我正在尝试实现一种向鼠标位置发射子弹的方法。我不知道它的数学或逻辑。这是一款 2D 俯视游戏。我让子弹向右发射并在某一点结束。我需要知道向鼠标位置开火的逻辑,而不是仅仅向 x 位置加 1。
使用atan2求出子弹原点与鼠标光标的夹角。然后使用 Sin 和 Cos 计算子弹的 x 和 y 速度。
伪代码
public void ShootBullet()
{
double bulletVelocity = 1.0; //however fast you want your bullet to travel
//mouseX/Y = current x/y location of the mouse
//originX/Y = x/y location of where the bullet is being shot from
double angle = Math.Atan2(mouseX - originX, mouseY - originY);
double xVelocity = (bulletVelocity) * Math.Cos(angle);
double yVelocity = (bulletVelocity) * Math.Sin(angle);
}
这是我生成射弹的代码。
public void spawnProjectile(Input input) {
double mouseX = 0;
double mouseY = 0;
double xVel;
double yVel;
double angle;
if (timer > 0) {
timer--;
}
if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
mouseX = input.getMouseX();
mouseY = input.getMouseY();
if (projectiles.size() < 1 && timer <= 0) {
projectiles.add(new Projectile((int) x + 8, (int) y + 8, 8, 8));
}
}
if (projectiles.size() > 0) {
for (int i = 0; i < projectiles.size(); i++) {
projectiles.get(i).update(input);
double originX = x;
double originY = y;
angle = Math.atan2(mouseX - originX, mouseY - originY);
xVel = (bulletVel) * Math.cos(angle);
yVel = (bulletVel) * Math.sin(angle);
projectiles.get(i).x += xVel;
projectiles.get(i).y += yVel;
if (projectiles.get(i).timer == 0) {
projectiles.remove();
}
}
}
}