Make a ball move at a speed to where the mouse is clicked

I’m new to processing and I’m trying to move a ball (an ellipse) to the position of where the mouse is clicked but I don’t what it to jump there . I want it to move there at a certain speed .

int golfBallX = 200;
int golfBallY = 150;
final int GOLF_SIZE = 30; // size of the golf
final int SPEED = 10; // the ball should move at this speed
void setup(){
  size(500 , 500); //canvas size
}

void draw(){
   drawBall();
}

void drawBall(){
  fill(255);
   ellipse(golfBallX ,golfBallY ,GOLF_SIZE,GOLF_SIZE);
}

void mouseClicked(){
     golfBallX = pmouseX;
     golfBallY = pmouseY;
}

Here’s one approach:

class GolfBall {
  PVector cp, tp;
  final float z=30, s=10; 
  GolfBall() {
    cp = new PVector( 250, 250 );
    tp = new PVector( 250, 250 );
  }
  void draw() {
    simulate();
    render();
  }
  void simulate() {
    PVector d = new PVector( tp.x-cp.x, tp.y-cp.y );
    d.limit(s);
    cp.x += d.x;
    cp.y += d.y;
  }
  void render() {
    pushMatrix();
    translate(cp.x, cp.y);
    fill(255);
    ellipse(0, 0, z, z);
    popMatrix();
  }
  void new_target( float x, float y ) {
    tp.x = x;
    tp.y = y;
  }
}

GolfBall ball = new GolfBall();

void setup() {
  size(500, 500);
}

void draw() {
  background(0, 100, 0);
  ball.draw();
}

void mousePressed() {
  ball.new_target( mouseX, mouseY );
}

Notice that the magic is happening inside the simulate() method. The ball is now tracking two positions. One is the ball’s current position, cp. The other is the ball’s target position, tp. To simulate movement, each frame, it finds the vector that is the direction, d, that points from the current position to the target position. It then limits this vector to the length of s, the speed of the ball, and uses it to update the current position.

1 Like