Using processing found at http://www.processing.org

Continueing from here 6

We saw that we could make the ball move up and down as though a force was being applied only by playing with acceleration!

Similarly, if we want the bal to move towards the mouse, we just .  . . play with the acceleration.

Exploring the logic behind

we need the ball to move towards the mouse,

we must have two vector points one mouse one ball location

since it’s towards mouse we do

mouse – ball location

we normalise so that we can adjust the distance between them

we multiply according to wish //setMag() is normalise and mult in one

Now, for it to take effect, we put acceleration = the vector above. Let us begin :

The moving towards mouse ball class :

PVector velocity;
PVector location;
PVector acceleration;

ball(){
 location = new PVector(width/2,height/2);
 velocity = new PVector(0,0);
 acceleration = new PVector(0,0);
}

void move(){
//or update()
  PVector mouse = new PVector(mouseX,mouseY);
  mouse.sub(location);
  mouse.setMag(0.5);
  
  acceleration=mouse;
location.add(velocity);
velocity.add(acceleration);

velocity.limit(5);
}

void bounce(){
  if(location.x>width ||location.xif(location.y>height||location.yvoid display(){
ellipse(location.x,location.y,20,20);
}

}

code in main function :

ball b;
void setup(){
  size(500,500);
   b = new ball();
}

void draw(){
 
background(0);
b.move();
b.bounce();
b.display();
}

Drop a comment if you need more explanations !

Run and you’ll see the ball following the mouse !

 Don’t forget to read explanations at the beginning.

try also velocity = mouse;

Advertisements