0
votes

I'm creating a little game in Javascript and I have created a collision detection function that detects when my 2 images collide. I have a player image and enemy image and I move the player around with the arrow keys. When I collide with the enemy image I want the player to not be able to cross over the image but still be able to move, like colliding with a wall or something. I don't really know how to go about this so I cant supply and example code but I can give you my collide function and player objects;

//PLAYER OBJECTS

var playerImg = new Image();
playerImg.src = "../Images/player.png";
var playerReady = false;
playerImg.onload = function(){
        playerReady = true;
};
var player = {
        x: 300,
        y: 150,
        speed: 200
};

//COLLIDE FUNCTION

function CollisionCheck(Img1, Img2, Obj1, Obj2, width){
    var colliding = false;

    if(Obj1.x < Obj2.x + width && Obj1.x + width > Obj2.x && Obj1.y < Obj2.y + width && Obj1.y + width > Obj2.y){
        colliding = true;
    }else{
        colliding = false;
    }

    return colliding;
}

Maybe I could detect which side the collision is on and stop the player from moving towards the image whilst colliding?

I call the function with:

if(CollisionCheck(player, enemy, 32)){

}
1
You can do your collision check before moving the object, for the intended location, and only move if there's no collision at that point.dhc

1 Answers

0
votes
function checkTouching(img1, img2)
{
    // checks if the two images are touching at any coordinate
    // given two objects with x, y, width, and height
    var touching =
        img1.x + img1.width >= img2.x
        && img1.x <= img1.x + img1.width
        && img1.height + img1.y >= img2.y
        && img2.y <= img2.y + img2.y;

    if (touching)
    {
        // images are touching
    }
    else
    {
        // images aren't touching
    }
}