Distance between two objects

Hello i want to calculate the distance between the centre of Pac-Man and the centre of the treat and If this distance is less than the radius of Pac-Man, we will consider Pac-Man to have “eaten” the treat. When Pac-Man has “eaten” the treat, make the treat reappear in a new random location

void generateTreat() { 
  treatX = random(width-1);
  treatY = random(height-1);
}

void drawTreat() {
  circle(treatX, treatY, TREAT_SIZE);
}

void eatTreat() {
  float distance = sqrt(sq(pacmanY-pacmanX)+sq(treatY-treatX));
  if (distance < PACMAN_DIAMETER) {
    circle(treatX, treatY, TREAT_SIZE);
  }
}

Thanks for the help

Draw yourself a diagram! Heck, I’ll draw you one!

To work out the (purple) distance, you need to take the square root of the sum of the squares of the change in the X position (blue) and Y positions (green).

How can you work out the lengths of the blue and green lines?

Compare that with what you’re doing! Do you see the problem?

Hello,

You may have to start with some basics first…

There are lots of resources (tutorials, references, examples, books, etc.) here:
processing.org

Check out the examples that come with Processing.
These are in the menu under File > Examples…> :

image

Also check out YouTube for the Coding Train.

Functions:
https://www.youtube.com/watch?v=zBo2D3Myo6Q
https://happycoding.io/tutorials/processing/creating-functions

Try it without functions first and once that is working then add functions.

Template with setup() and draw() < Click to open
// Variable declarations
// https://processing.org/examples/variablescope.html

int number;

// setup() runs only once
//https://processing.org/reference/setup_.html
void setup() 
	{
  size(200, 200);
  // Code here...
  }

// draw() continuously loops
// https://processing.org/reference/draw_.html
void draw() 
	{
  background(0);
	// Code here...
  }

I do not know what the scope of your homework is… there may be a function already available to do this.

You have to do this work and find it in the available references.

I recommend you write your own function to learn how to do this.

:)

Hello @MacJ

This Abe Pazos tutorial may be of help. There is a built-in distance function in processing – dist() – that I think will make your task easier.
Do not get distracted by the use of noise() in the tutorial, just focus on the implementation of dist().

Since you don’t show setup() or draw() in your code, I’m not sure what your overall thought process is… but provided you’ve worked that all out…

Good luck!
:nerd_face: