【问题标题】:Why wont my image move when the y value of it is increasing?为什么当图像的 y 值增加时我的图像不会移动?
【发布时间】:2021-08-29 04:54:36
【问题描述】:

我目前遇到的问题是,当图像的 y 值增加时,图像不会移动。我想让图像垂直移动,所以我做了一个方法来控制图像的速度,参数是 ActionEvent 和播放器的 y 值。当我打印出该值时,y 值会增加,但图像不会移动。我什至添加了根本不让图像移动的计时器。输出中没有任何错误。

 public void speedPerformed(ActionEvent e, Rectangle movingPlayer){
        int speed = 15;
        // help deals with gravity
        ticks++;
        
         
        // if the remainder of zero is given from tick
        //then the object will feel heavier
        if (ticks % 2 == 0 && yMotion < 15) {
            yMotion += 3;
        
        }
        movingPlayer.y += yMotion;
       
    }


 @Override
    public void actionPerformed(ActionEvent e) {
        
        action.speedPerformed(e,movingPlayer);
        gameInterface.getRenderer().repaint();
       
        
    }

public void repaint(Graphics g) {
 
       g.drawImage(Renderer.renderer.getImage(),movingPlayer.x,movingPlayer.y,100,100, null);
    
    }




public RepaintConfiguration(GameInterface gameInterface) {
      this.gameInterface = gameInterface;
      lasers = new Lasers();
      action = new Actions();
      movingPlayer = new Rectangle(0, 550, 100, 100);
      timer = new Timer(20,this);
      timer.start();
    }

如果您想查看我未在此处包含的任何代码,请告诉我。

【问题讨论】:

  • 仍然不知道为什么代码的结构如此复杂。正如您在上一个问题中所述,您应该只在游戏面板中进行游戏渲染。当调用 Timer 并重新绘制游戏面板时,您要绘制的每个对象的状态都会更新。有关基本示例,请参阅:stackoverflow.com/questions/54028090/…
  • 它能帮我解决图片无法移动的问题吗?
  • 那么当你测试代码时发生了什么?您是否看到面板周围有物体移动?
  • 其实..我解决了这个问题。

标签: java image swing actionlistener repaint


【解决方案1】:

您的代码错误:您正在更新局部变量y

你应该直接更新movingPlayer:

public void speedPerformed(ActionEvent e){ 国际速度= 15; // 帮助处理重力 滴答声++;

    // the y value of the moving player
    
    // if the remainder of zero is given from tick
    //then the object will feel heavier
    if (ticks % 2 == 0 && yMotion < 15) {
        yMotion += 3;
    
    }
    movingPlayer.y += yMotion;
   
}

【讨论】:

  • 所以...我试过了,还是不行。
猜你喜欢
  • 1970-01-01
  • 2017-03-12
  • 2014-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-05
  • 2016-05-02
  • 1970-01-01
相关资源
最近更新 更多