4.4 Cuts

A function that is used very often in combination with shapes is Cuts. There are quite a lot of different versions of this function, but its meaning is always the same: do two shapes overlap, or don’t they? The Cuts function allows you to check if a dot is inside a circle, if a circle (partially) overlaps a rectangle, if a line cuts a rectangle and so on.

To check if a dot is inside a circle, use the code below:

 
Vec2 pos(0.1, 0.1); 
Circle area(0.3, Vec2(0)); 
 
if(Cuts(pos, area)) area.draw(RED);  
5

Of course, in this example it is already certain the dot will always be inside the circle. But you could use the same principle to see if the mouse pointer is inside the circle, like this:

 
Circle area(0.1, Vec2(0)); 
 
if(Cuts(Ms.pos(), area)) area.draw(RED); 
else area.draw(BLACK);  
5

The code above is the starting point for many possible interactions. Often, this will be in combination with other rules. Try to find out what the code below does:

 
Rect button(Vec2(-0.2, -0.1), Vec2(0.2, 0.1)); 
bool hover = false
 
// in the update function: 
5if (Cuts(Ms.pos(), button)) { 
    hover = true
  if(Ms.bp(0)) exit(); 
} else hover = false
 
10// in the draw function: 
if(hover) { 
  button.draw(Color(0, 255, 0)); 
} else { 
  button.draw(Color(0, 155, 0)); 
15}  

Exercise
  1. Create an application with 3 circles, each one below the other. Only the border of the circles is drawn, unless the mouse pointer is in that particular circle. In which case you draw a filled circle.
  2. Make the circles move slowly to the right as long as the mouse pointer is inside the circle.
  3. Create an integer ‘score’. When the circle goes over the right side of the screen, increase the score by one and place the circle back in the middle.

Exercise
(A bit harder) Create your own class that behaves like a button, with a hover effect. The button also needs a line of text, which will be set by the create function.