制作一个简单的游戏,我点击屏幕,火箭因点击而从左向右移动。当我单击时,它从 mouseY 获取 y 位置,并具有初始化的 x,该 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();
}
最佳答案
添加一个属性来说明火箭何时启动,并向类 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
,设置对象火箭上的 y 坐标:
void mousePressed() {
if (mouseButton == LEFT) {4
rocket.setY(mouseY);
}
}
请注意,该事件仅在按下鼠标按钮时发生一次。
关于java - 如果我移动鼠标,鼠标单击停止移动后触发移动的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55533785/