0
votes

So I understand that I'm not coding this the best way possible at the moment; this is a sort of test run. What I'm trying to do is wall collisions using rectangles and the intersects property (sorry if I'm not using the correct terminology). So far I have 2 rectangles on screen. 1 the player controls and the other which the play is colliding with. When they collide the player stops moving. The problem is that if the player is trying to move into the rectangle while they are already colliding then the player can't move in any direction perpendicular to the movement ie if the player is holding the right arrow key moving into the rectangle, then they cannot move up or down. The game works on the premise that if your x or y coordinates aren't valid, then you will be moved back to the last valid coordinate recorded but I'm having trouble detecting the valid x and y coordinate separately. Here is the code:

public void Collision() 
{

    if(x < 0)
        x = 0;

    if(x > 400 - width)
        x = 400 - width;

    if(y < 0)
        y = 0;

    if(y > 300 - height)
        y = 300 - height;


    rect1 = new Rectangle(x, y, 16, 16);
    rect2 = new Rectangle(sx, sy, wid, hei);

    if(!rect1.intersects(rect2))
    {
        validX = true;
        validY = true;
    }
    else
    {
        validX = false;
        validY = false;
    }


    if(validX)
    {
        lastValidX = x;
    }

    if(validY)
    {
        lastValidY = y;
    }

    if(!validX)
    {
        x = lastValidX;
    }

    if(!validY)
    {
        y = lastValidY;
    }

}

The Collision() method in the Guy class is where I'm having the trouble I believe. Yes my code is pretty messy right now but this is only a test.

Thanks, David.

1
Can you please narrow your code? Leaving only the needed part - Tala
I think you need to learn about proper game development such as double buffering, game loops, etc. I could give you a tutorial if you'd like? - Josh M
Okay I've narrowed my code down to what I think is the only relevant part. I do know about buffering kind of and proper game loops instead of using a timer like I was but I'm just doing this for a school project and so I think that's a bit more difficult than what I need to be doing. - DaBoydMan

1 Answers

1
votes

You can implement what you're describing by doing extra logic around here (i.e. detecting cases when one is false and the other is true):

if(!rect1.intersects(rect2))
{
    validX = true;
    validY = true;
}
else
{
    validX = false;
    validY = false;
}

However, it seems like maybe you shouldn't be allowing the rectangles to ever be in a "colliding" state in the first place. For example, you can change the Move method to do something like

public void Move()
{
    int oldX = x, oldY = y;
    x += dx;
    y += dy;
    if (Collision()) {
        x = oldX;
        y = oldY;
    }
}