Making a simple game where i click on the screen and a rocket moves left to right because of the click. It gets its y position from mouseY when i click and has an initialised x which begins to change after the click. The problem is simply moving the mouse whilst the object is moving causes it to stop and another problem is holding the left mouse button down makes makes the y change continuously with mouseY which i don't want. Clicking again makes the object move from x position where it left off and jumps to new mouseY. I want the Y to be set after the first click. How would i fix these issues? thanks a lot in advance for any help.
I don't really know what to try as i don't know whats causing it to stop moving.
Rocket class
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();
}
}
Main sketch
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();
}
Add an attribute which stated when the rocket was started and add a method to the class Rocket
which changes the y coordinate and starts the rocket:
class Rocket
{
boolean started = false;
// [...]
void setY(int newY) {
this.y = newY;
started = true;
}
void mouseClicked() {
if (started) {
this.x = x+5;
}
}
}
Implement the mousePressed
, which set the y coordinate on the object rocket
:
void mousePressed() {
if (mouseButton == LEFT) {4
rocket.setY(mouseY);
}
}
Note, the event only occurs once when the mouse button is pressed.