我想在方法中更改对象的变量y的值,但是this.y引用计时器而不是对象

private void move(byte direction) {
        Timer projectilemovement = new Timer();
        projectilemovement.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                switch (direction){
                    case 1:
                        this.y -= speed; // object to be changed
                        break;
                }
            }
        }, 0, 16);
    }


编辑:
我可能说错了,
我想制作一个游戏,玩家可以朝特定方向射击弹丸
所以我有这个代码

public class Projectile {
    int x, y;
    int sizex, sizey, examplesizex = 10, examplesizey = 20;
    byte speed = 2;

    public Projectile(byte rotation) {
        switch (rotation){
            case 1:
                this.sizex = examplesizex;
                this.sizey = examplesizey;
                this.x = Player.x + (Player.sizex/2) /*mid of player*/ - this.sizex/2;
                this.y = Player.y;
                move(rotation);
                break;
            //TODO: other rotations

        }
    }


(然后是前面的代码)

此刻,每当我按下一个按钮,它就会在播放器方法new Projectile(rotation);中执行

您是否有更好的方法来射击弹丸?

最佳答案

据我所知,您应该不用this关键字就能做到,因为y是一个不会被方法参数或局部变量覆盖的字段。也许我缺少更多信息?

您要的是this post吗?

关于java - 不能在Timer中的类的访问变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58939977/

10-10 01:07
查看更多