You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:LibGDX中实现Actor跟随动态移动Actor的方法

在LibGDX中实现Actor动态跟随移动目标的方案

MoveToAction的问题在于它初始化时就固定了目标坐标,不会随目标Actor的移动动态更新。下面是几种可行的解决方案:

方案一:自定义跟随Action

继承LibGDX的TemporalAction,在每一帧更新时获取目标的最新坐标,计算当前应该到达的位置:

import com.badlogic.gdx.scenes.scene2d.actions.TemporalAction;
import com.badlogic.gdx.scenes.scene2d.Actor;

public class FollowAction extends TemporalAction {
    private Actor target;

    public FollowAction(Actor target, float duration) {
        super(duration);
        this.target = target;
    }

    @Override
    protected void update(float percent) {
        if (target == null) return;
        // 按时间进度插值计算当前位置,保持平滑跟随
        float currentX = actor.getX() + (target.getX() - actor.getX()) * percent;
        float currentY = actor.getY() + (target.getY() - actor.getY()) * percent;
        actor.setPosition(currentX, currentY);
    }
}

使用方式:

game_element = new GameContainer();
stage.addActor(game_element);
// 2秒内平滑跟随玩家的动态位置
game_element.addAction(new FollowAction(player, 2));

方案二:在Actor的act方法中处理跟随逻辑

直接在需要跟随的Actor的act方法里编写逻辑,这种方式更灵活,方便添加额外规则(比如距离阈值、跟随速度控制):

修改你的GameContainer类:

import com.badlogic.gdx.scenes.scene2d.Actor;

public class GameContainer extends Actor {
    private Actor followTarget;
    private float followSpeed = 100f; // 每秒移动的像素数,可根据需求调整

    public void setFollowTarget(Actor target) {
        this.followTarget = target;
    }

    @Override
    public void act(float delta) {
        super.act(delta);
        if (followTarget == null) return;

        // 计算与目标的距离和方向
        float dx = followTarget.getX() - getX();
        float dy = followTarget.getY() - getY();
        float distance = (float) Math.sqrt(dx * dx + dy * dy);

        // 距离过近时停止移动,避免抖动
        if (distance > 2f) {
            float moveRatio = followSpeed * delta / distance;
            setPosition(getX() + dx * moveRatio, getY() + dy * moveRatio);
        }
    }
}

使用方式:

game_element = new GameContainer();
stage.addActor(game_element);
game_element.setFollowTarget(player);

方案三:动态更新MoveToAction(不推荐)

通过循环执行run动作,每一帧清除旧的MoveToAction并创建新的,这种方式会频繁创建和销毁动作,可能有性能损耗:

game_element.addAction(Actions.forever(Actions.run(() -> {
    game_element.clearActions();
    // 用较短的duration实现近似跟随效果
    game_element.addAction(Actions.moveTo(player.getX(), player.getY(), 0.3f));
})));

内容的提问来源于stack exchange,提问作者EgVos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 19:50:11