如果我移动鼠标,鼠标单击停止移动后触发对象移动

问题描述 投票:1回答:1

制作一个简单的游戏,我点击屏幕,火箭由于点击而从左向右移动。当我点击它并从初始化的x开始在点击后开始改变时,它从mouseY获得y位置。问题是只是在物体移动时移动鼠标导致它停止而另一个问题是按住鼠标左键使得y使得我不想要的鼠标Y连续变化。再次单击使对象从其停止的x位置移动并跳转到新鼠标Y。我希望在第一次点击后设置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个回答
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);  
    }
}   

请注意,只有按下鼠标按钮时才会发生一次事件。

© www.soinside.com 2019 - 2024. All rights reserved.