user14368147
user14368147

Reputation:

Collision, how to use collision when object hits the other

So I needed some assistance on how I can get my screen to say 'game over you win' if a mini square hits (shot at) the circle... and 'you lose' if any ONE of the circles makes it to the left of the screen without a mini square being shot at it and then the game restarts. I've been a bit confused. I don't know if I should use the dist() function or something else.

Upvotes: 2

Views: 692

Answers (1)

KamielDev
KamielDev

Reputation: 569

You need to look into implementing some form of collision detection between your circles and squares.

Take a look at this website which offers a great explanation on how to detect circle/rectangle collisions: http://www.jeffreythompson.org/collision-detection/circle-rect.php (Check out the rest of the website too, it's amazing!)

When you have written your collision function, the simplest way to get your game working is to check for a collision between every square you shoot, and every circle. I'd suggest using an OOP approach so you can treat your squares and circles as objects with their own functions, but that's up for you to decide. My pseudocode is written with OOP in mind, but the principle of the code you'd have to write stays the same.

Pseudocode:

bool CheckForGameEnd()
{
    foreach(Circle circle)
    {
        foreach(Rectangle rectangle)
        {
            // CheckForCollision() is your collision detection function and 
            // returns true or false depending on whether a collision has been found.
            if (CheckForCollision(circle, rectangle))
            {
                return true;
            }
        }
    }
    return false;
}

Your draw function would look something like this (pseudocode):

void Draw()
{
        if (gameWon)
        {
            Background("black");
            Text("i won");
            // Dont bother with the rest of the function if game has been won
            return;
        }

        if (CheckForGameEnd())
        {
            gameWon = true;
            // Dont bother with the rest of the function if game has been won
            return;
        }

        // game code whilst not won runs here
        foo();
        bar();
}

Upvotes: 2

Related Questions