0

How can I make the mouse move like a joystick. Here is a example of what I mean except this only moves to the right and when the mouse is all the way to the right it stops. I want the circle to stop if the mouse is at the center and move where ever the mouse is.


float ballX = 0;  // need to keep track of the ball's current position

float ballY = 150;

void setup() {
  size(300,300); // standard size
}


void draw() {
  background(200);  // dull background
  float speed = 2.0 * ( mouseX / (width*1.0) );
  println("speed is " + speed); // print just to check
  ballX = ballX + speed;  // adjust position for current movement


  fill(255,0,0);
  ellipse(ballX, ballY, 20,20);
}
EdtheBig
  • 161
  • 1
  • 2
  • 7

1 Answers1

0

You want to check the mouseX position against the center of the window, which is width/2.

To find the relative position of the mouse, simply subtract that center position from your mouse position. That way when the mouse is to the left of the center, that value is negative, and your ball will move to the left.

You might also want to keep your ball on the screen.

float ballX = 0;  // need to keep track of the ball's current position
float ballY = 150;

void setup() {
  size(300,300); // standard size
}


void draw() {

  float centerX = width/2;
  float maxDeltaMouseX = width/2;
  float deltaMouseX = mouseX-centerX;
  float speedX = deltaMouseX/maxDeltaMouseX;

  background(200);  // dull background
  println("speed is " + speedX); // print just to check
  ballX = ballX + speedX;  // adjust position for current movement


  //keep ball on screen
  if(ballX < 0){
    ballX = 0;
  }
  else if(ballX > width){
    ballX = width;
  }

  fill(255,0,0);
  ellipse(ballX, ballY, 20,20);
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107