Loading...
Logo
Processing Forum
Hey people.

I'm working on a game at the moment, I am stuck on something at the moment. I want to create a line which starts from a static starting position, and when I click it will gradually move towards where the mouse was clicked.

The code below shows what I want to achieve.

int endX;
int endY;
int endvar;
int startX;

void setup() {
  size(500, 500);
  startX = (int)random(150, 300);
  endY = 0;
  endvar = (int)random(-1 , 2);
  endX = startX;
 
}

void draw(){
  background (255);
  smooth();
  stroke(255,0,0);
  line(startX, 0, endX, endY);
  endY++;
  endX = endX + endvar;
}

(That is part of a separate section).

This is the code I have so far -

int endX;
int endY;
int startX;
int startY;

void setup(){
 size(500, 500);
 startX = 250;
 startY = 480;

}


void draw(){
  background (255);
 smooth();
 stroke(0,255,255);
}

void mousePressed() {
 
  smooth();
  stroke(255,0,0);
  line(250, 480, mouseX, mouseY);
}

I've tried integrating both pieces of code together, but this hasn't seemed to work at all and I think I need some sort of variable system. Could somebody lend me a hand with this?

Replies(3)

Store mouseX and mouseY in two global variables when mousePressed() is called, and make the line to move toward this point.
For example, take the difference between the current position of the line and the target, divide by a number of steps, and you get a value you can use to change the coordinates on each frame (like your endvar, whose name isn't representative of its usage).
Ok. I'll try that.

So you would mean storing them in a variable like this-

int posX = mouseX;
int posY = mouseY;

or an int posX; etc

and in the call to mouseClicked
posX = mouseX;
The second one.