# libgdx

# 2D

# 移动

移动 = 时间 * 速度

x += speed * delta

create():

player.setSize(100, 100);
playerX = 100;
playerY = 100;

render():

时间:

float delta = Gdx.graphics.getDeltaTime();
if (Gdx.input.isKeyPressed(Input.Keys.W)) {
    playerY += playerSpeed * delta;
}

防止玩家越界:

playerY = MathUtils.clamp(playerY, 0, Gdx.graphics.getHeight() - 100);
player.setPosition(playerX, playerY);

# 转向

鼠标坐标 - 玩家中心坐标 = 玩家到鼠标的距离,通过 atan2 计算弧度 * MathUtils.radiansToDegrees 得到角度

最终 setRotation (playerAngle)

获取鼠标 x,y 坐标:

  • 注意:libgdx 中的坐标系与 windows 的坐标系相反 所以 y 轴需要 高度 - 鼠标 y 轴 = 实际鼠标 y 轴
// 鼠标在游戏中的坐标
float mouseX = Gdx.input.getX();
float mouseY = Gdx.graphics.getHeight() - Gdx.input.getY();

计算玩家中心:

// 玩家中心
float playerCenterX = playerX + player.getWidth() / 2f;
float playerCenterY = playerY + player.getHeight() / 2f;

计算玩家到鼠标的距离:

float dx = mouseX - playerCenterX;
float dy = mouseY - playerCenterY;

计算角度:

playerAngle = MathUtils.atan2(dy, dx) * MathUtils.radiansToDegrees;

atan2=dy/dx (弧度)*57.2 = 角度

player.setRotation(playerAngle);

# 子弹

查看转向,需要通过计算的鼠标距离来完成计算子弹移动

公式:

玩家到鼠标坐标距离的 2 次方相加 = 根号结果 = 玩家到鼠标的斜边长度

玩家到鼠标距离坐标 / 斜边长度 = 子弹方向

子弹移动 = 子弹方向 * 子弹速度 * 时间

bullet.x += bullet.dirX * bulletSpeed * delta;
bullet.y += bullet.dirY * bulletSpeed * delta;

image-20260926191538811

private float jg = 0.0f; // 子弹发射间隔
private float cz = 0.1f; // 重置发射时间
jg -= delta;
if (Gdx.input.isButtonPressed(Input.Buttons.LEFT) && jg <= 0.0f) {
    float length = (float) Math.sqrt(dx * dx + dy * dy);
    if (length > 0.001f) {
        float dirX = dx / length;
        float dirY = dy / length;
        bullets.add(new Bullet(playerCenterX - 5, playerCenterY - 5, dirX, dirY, 10, 10));
        jg = cz;
    }
}
更新于

请我喝[茶]~( ̄▽ ̄)~*

D 微信支付

微信支付

D 支付宝

支付宝

D 贝宝

贝宝