Search code examples
javascriptlocationspritecollision-detectionp5.js

How do I have a sprite in a group have the same position as another sprite not in a group upon collision?


In p5.js, I am having trouble with having sprites in a group locking onto the same position as the player sprite upon collision.

function draw () {
   traySprite.collide(toppingsGroup, toppingsTouch)
}
function toppingsTouch(player, topping) {
   topping.position.x = traySprite.position.x;
   topping.position.y = traySprite.position.y;
   topping.velocity.x = 0;
}

toppingsGroup includes five different sprites, and I want to have it so that when one of the sprites collides with traySprite, that singular sprite from the group locks onto the same position as traySprite, without affecting any of the other sprites in that group. This should apply to all of them, but the issue I am having is that once one of the sprites collides with traySprite, it quickly but visibly phases out of the canvas.

**edit - I changed traySprite.position.x and traySprite.position.y to player.position, and expectedly, the problem is still the same. I just thought I would clear that up.


Solution

  • Okay so after looking at the reference for p5.js, I have figured out that using traySprite.overlap is what I need rather than traySprite.collide.

    This is because with the overlap function, it simply checks to see if the sprites have overlapped eachother, rather than actually causing them to physically interact with the collide function.

    function draw() {
       traySprite.overlap(toppingsGroup, toppingsTouch);
    }
    
    
    function toppingsTouch(player, topping) {
       topping.position.x = traySprite.position.x;
       topping.position.y = traySprite.position.y;
       topping.velocity.x = 0;
       topping.velocity.y = 0;
    }
    

    This is what my code ended up looking like. With the collide function they were constantly colliding with eachother so it caused them to phase out of the screen, whilst with overlap they simply phase through eachother, so they can have the same position.