0

I have followed the instructions of a "TheCodingTrain" tutorial, it describes how to calculate the distance between two circles to emulate collisions. I have a lot more, but this is the code I have pertaining to my problem.

  playerPos = createVector(width * 0.2, height / 2, 60);
  enemyPos1 = createVector(width * 0.8, height / 2, 40);

  d = dist(playerPos.x,playerPos.y,enemyPos1.x,enemyPos1.y);

  circle(playerPos.x, playerPos.y, playerPos.z);
  circle(enemyPos1.x, enemyPos1.y, enemyPos1.z);

  if( d < playerPos.z/2 + enemyPos1.z/2){
     enemyPos1.x++
  }

I tried the code above, it did not make the position of the smaller circle change. I was expecting it to move. I have gone through and I haven't identified any problems with the code.

2
  • is d < playerPos.z/2 + enemyPos1.z/2 ? Commented Jul 28 at 3:14
  • Is this code inside the draw() function? Changing the enemyPos1 position won't affect the position if you overwrite it in the next cycle anyway with 'createVector'.
    – Kroepniek
    Commented Jul 29 at 13:12

1 Answer 1

1

You don't have any code to create movement. You have two circles which don't overlap, and aren't moving so will not overlap. Generally one uses a velocity vector that is added to the position to create movement. Then, when the circles actually overlap, your collision detection code will work:

let playerPos, enemyPos1;

function setup() {
  createCanvas(400, 400);
  playerPos = createVector(width * 0.2, height / 2, 60);
  enemyPos1 = createVector(width * 0.8, height / 2, 40);
  playerSpd = createVector(1, 0, 0);
  enemySpd1 = createVector(-1,0,0);
}

function draw() {
  background(255);
  d = dist(playerPos.x, playerPos.y, enemyPos1.x, enemyPos1.y);

  circle(playerPos.x, playerPos.y, playerPos.z);
  circle(enemyPos1.x, enemyPos1.y, enemyPos1.z);

  if (d < playerPos.z / 2 + enemyPos1.z / 2) {
    console.log("hit");
  }
  
  playerPos = playerPos.add(playerSpd);
  enemyPos1 = enemyPos1.add(enemySpd1);
}

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.