【问题标题】:Object triggered to move after mouse click stops moving if i then move the mouse如果我然后移动鼠标,则在鼠标单击停止移动后触发对象移动
【发布时间】:2019-04-05 10:50:47
【问题描述】:

制作一个简单的游戏,我点击屏幕,火箭会因为点击而从左向右移动。当我单击时,它从 mouseY 获取它的 y 位置,并有一个初始化的 x,它在单击后开始改变。问题只是在对象移动时移动鼠标会导致它停止,另一个问题是按住鼠标左键会使 y 与 mouseY 连续变化,这是我不想要的。再次单击会使对象从停止的 x 位置移动并跳转到新的 mouseY。我希望在第一次单击后设置 Y。我将如何解决这些问题?非常感谢您的帮助。

我真的不知道该尝试什么,因为我不知道是什么导致它停止移动。

火箭类

class Rocket
{ 
  int x = -100;
  int y;


  void render()
  {
    fill(153,153,153);
    rect(x,y,40,10);  //rocket body  
    fill(255,0,0);
    triangle(x+60,y+5,x+40,y-5,x+40,y+15);  //rocket head
    triangle(x+10,y+10,x,y+15,x,y+10);  //bottom fin
    triangle(x+10,y,x,y,x,y-5);  //top fin
    fill(226,56,34);
    stroke(226,56,34);
    triangle(x-40,y+5,x,y,x,y+10);  //fire
    fill(226,120,34);
    stroke(226,120,34);
    triangle(x-20,y+5,x,y,x,y+10);  //fire
  } 
  void mouseClicked()
  {
    if (mouseButton == LEFT)
    {
      y = mouseY;
      this.x = x+5;
    }
  }

  void update()
  {
    render();
    mouseClicked();
  }
}

主要草图

ArrayList<Alien> aliens = new ArrayList<Alien>();
Rocket rocket;

void setup()
{
  size(1200,900);
  for (int i = 0; i < 5; i++)
  {
    aliens.add(new Alien());
  }
  rocket = new Rocket();
}

void draw()
{
  background(0);
  moon(); 
  for (int i = aliens.size()-1; i >= 0; i--)
  {
    aliens.get(i).update();
    if (aliens.get(i).CheckHit())
    {
      aliens.remove(i);
    }
  } 
  rocket.update();
}

【问题讨论】:

    标签: java processing mouseclick-event


    【解决方案1】:

    添加一个说明火箭何时启动的属性,并向Rocket 类添加一个方法,该方法更改y 坐标并启动火箭:

    class Rocket
    {
        boolean started = false;
    
        // [...]
    
    
        void setY(int newY) {
            this.y = newY;
            started = true;
        }
    
        void mouseClicked() {
    
            if (started) {
                this.x = x+5;
            }
        }
    } 
    

    实现mousePressed,设置对象rocket的y坐标:

    void mousePressed() {
    
        if (mouseButton == LEFT) {4
            rocket.setY(mouseY);  
        }
    }   
    

    注意,该事件仅在按下鼠标按钮时发生一次。

    【讨论】:

    • 感谢您的回答,但如果鼠标在点击后稍微移动,火箭仍然会停止移动
    • @Jack 我已经尽力了,但很难理解你想要达到的目标。我扩展了答案。
    • 非常感谢,started 变量修复了问题对象现在在点击后无论如何都会继续移动。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多