【问题标题】:Image rotation happens too often图像旋转发生得太频繁
【发布时间】:2015-10-11 06:31:51
【问题描述】:

我正在为塔防游戏创建原型。现在,我正在攻击一些箭头(例如稍后从塔楼发射的子弹),它们应该指向四处奔跑的怪物的中心。我设法在第一个逻辑调用中相应地设置了旋转,但我不知道如何更改代码以防止发生以下情况:http://recordit.co/jBdXtGGeN8

简而言之:箭头一直在旋转,即使它应该旋转生成,然后只旋转小值以适应移动的怪物。

箭头的构造函数:

    public Shot(Vector2 position, EntityV2 target) {
        this.sprite = SpriteStore.get().getSprite("resources/sprites/arrowShot.png");   
        this.position = position;
        this.targetEntity = target;
        this.rotation = Math.atan2(targetEntity.getBounds().getCenterY()
            - position.getY(), targetEntity.getBounds()
            .getCenterX() - position.getX());
        this.rotation += Math.PI / 2.0;
        this.angle = Math.toDegrees(rotation);
        this.movementVector = new Vector2();
        bounds = new Rectangle((int) position.getX(), (int) position.getY(), sprite.getWidth(), sprite.getHeight());
    }

逻辑更新调用:

    public void move(float delta) {
        position.add((movementVector.getX() * delta) / 1000, (movementVector.getY() * delta) / 1000);

        if(targetEntity.getBounds().contains(position.getX(), position.getY())) {
            isDone = true;
        }
        bounds.setLocation((int) position.getX(), (int) position.getY());


        rotation = Math.atan2(targetEntity.getBounds().getCenterY()
                - position.getY(), targetEntity.getBounds()
                .getCenterX() - position.getX());
        rotation += Math.PI / 2.0;
        angle = Math.toDegrees(rotation);

        calculateMovementVector(targetEntity.getCenter());      
    }

渲染调用:

public void draw(Graphics2D g) {
    int x = (int) position.getX() + sprite.getWidth()/2;
    int y = (int) position.getY() + sprite.getHeight()/2;
    g.rotate(angle, x, y);
    sprite.draw(g, (int) position.getX(), (int) position.getY());
    g.rotate(-angle, x, y);
}

我计算运动矢量的方式(应用于位置):

private void calculateMovementVector(Vector2 to) {
    float dX = to.getX() - (float) bounds.getCenterX();
    float dY = to.getY() - (float) bounds.getCenterY();
    float distance = (float) Math.sqrt(dX * dX + dY * dY);
    float sX = speed * dX / distance;
    float sY = speed * dY / distance;
    movementVector.set(sX, sY);
}

【问题讨论】:

    标签: java math rotation game-physics image-rotation


    【解决方案1】:

    我假设您的 Graphics2D 对象是 java.awt.Graphics2D 的一个实例。也就是说,我想我知道你的问题:

    the documentation for rotate() 指定您应该传入一个弧度值时,您正在使用度数。由于以度为单位的测量与以弧度为单位的测量范围非常不同,因此您会发现度数的微小变化会导致弧度的非常大(可能超过一个完整的圆)变化。尝试注释掉度数转换,并使用rotation 而不是angle 调用g.rotate()

    【讨论】:

    • 我想我应该更频繁地阅读文档:/ 非常感谢,它成功了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 2023-03-29
    • 2016-06-02
    • 1970-01-01
    相关资源
    最近更新 更多