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(){

void drawBall(){
   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() {
  void simulate() {
    PVector d = new PVector( tp.x-cp.x, tp.y-cp.y );
    cp.x += d.x;
    cp.y += d.y;
  void render() {
    translate(cp.x, cp.y);
    ellipse(0, 0, z, z);
  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);

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