1

PD: I'M PRETTY NEW AT THIS SO I'M ONLY DOING THE BASICS

I have no idea on how to call out a function when two of my images collide. Here's my code:

var arbol;
var poma;
var pomaicono;
var cistell;
var y = [];
var x = [];
var v = [];
let font;

function setup() {
  createCanvas(400, 550);
  arbol = loadImage ("ARBOL.png");
  poma = loadImage ("POMA.png");
  pomaicono = loadImage ("POMA.png");
  cistell = loadImage ("CISTELL.png");
  font = loadFont ("dogica.otf");
  
  for (i = 0; i < 3; i = i + 1) {
    x[i] = int(random(0, 400));
    y[i] = int(random(0, 400));
  }
  
}

function draw() {
  background(65,105,255);
  image (arbol, 120, -320, 500, 500);
  image (arbol, -200, -320, 500, 500);
  image (cistell, mouseX, 440, 100, 100);
  image (pomaicono, 10,10,30,30);
  
  textFont(font);
  fill(220);
  textSize (25);
  stroke(0);
  strokeWeight(3);
  text("x1",47,37);
  
  for (i = 0; i < 3; i = i + 1) {
    image(poma, x[i], y[i], 50, 50);
    y[i] = y[i] + 3;
    if (y[i] > 440) {
      y[i] = 0;
      x[i] = int(random(0, 400));
    }
  }
  
  var d = dist(poma.x, cistell.x, poma.y, cistell.y);
  
  if (d < poma.x + cistell.x) {
  print("hola");
  }
 
}

What I wanted to happen is that when an apple touches the basket (depending on the position indicated by the mouse) it could call out an option and there's I could put what I wanted to happen after

1 Answer 1

1

What you can do is work with circles. For example, an invisible circle on the apple and another on the basket; if they touch each other, you call the function that you wanted.

The way to check collision between circles is to analyse that the distance between their centers is less than the sum of their radii. I recommend to do the collision check in the same interaction as the movement.

Generally, pixel-by-pixel collision check is far too costly to the computer and to solve this problem.

2
  • Thanks for your response!! Sorry if i'm a bother, but how do I make an invisible ellipse? And also, I have a random command, will the circle follow those? Commented Feb 23, 2023 at 20:09
  • Wouldn't rectangles be better for rectangular objects? I guess the apple would be a circle, presumably, so depending on OP's use case, a circle-rectangle collision might be in order.
    – ggorlen
    Commented Feb 24, 2023 at 2:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.