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

**URL:** <https://discourse.processing.org/t/make-a-ball-move-at-a-speed-to-where-the-mouse-is-clicked/4652>\
**Category:** Coding Questions\
**Created:** [October 19, 2018, 4:57pm UTC](https://discourse.processing.org/t/make-a-ball-move-at-a-speed-to-where-the-mouse-is-clicked/4652 "2018-10-19T16:57:39Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kome](https://avatars.discourse-cdn.com/v4/letter/k/13edae/32.png) [@kome](https://discourse.processing.org/u/kome)\
**Post date:** [October 19, 2018, 4:57pm UTC](https://discourse.processing.org/t/make-a-ball-move-at-a-speed-to-where-the-mouse-is-clicked/4652/1 "2018-10-19T16:57:39Z")

</div>

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 .

```auto
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;
}

```

---

<div class="post-metadata">

**Author:** ![TfGuy44](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/tfguy44/32/41_2.png) [@TfGuy44](https://discourse.processing.org/u/TfGuy44)\
**Post date:** [October 19, 2018, 6:20pm UTC](https://discourse.processing.org/t/make-a-ball-move-at-a-speed-to-where-the-mouse-is-clicked/4652/2 "2018-10-19T18:20:03Z")

</div>

Here’s one approach:

```auto
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.
