Вопрос

Sorry, I'm a total novice - I've searched for an answer to this but nothing quite matches what I am doing.

I have a basic arrow controlled maze game, with labels for "walls" , named Label1, Label2, etc.

When I press a key, it detects the intersection between the character and the walls.

I am doing this currently with a large nested if, as follows :

            if (PBoxPlayer.Bounds.IntersectsWith(LblWall1.Bounds))
            {
                PBoxPlayer.Location = new Point(CurrX - 10, CurrY);

            }

            else if (PBoxPlayer.Bounds.IntersectsWith(LblWall2.Bounds))
            {
                PBoxPlayer.Location = new Point(CurrX - 10, CurrY);

            }

            else if (PBoxPlayer.Bounds.IntersectsWith(LblWall3.Bounds))
            {
                PBoxPlayer.Location = new Point(CurrX - 10, CurrY);

            }

But this is becoming very messy.

Is there a way I can just say - if player hits 'any' wall, then move it back to it's previous position?

I realise the above is probably an bad way to code, but I am happy with the action on screen just not the repeating code behind it.

Это было полезно?

Решение

Start by putting all the "collision-interesting" objects into a collection, for example:

var walls = new[] { LblWall1, LblWall2, LblWall3 };

There's bound to be a better way to do this as well, but it's not obvious because there's no context for this. So keep that in mind and let's go on.

Having all the objects in a collection enables you to use LINQ:

var collision = walls.Any(w => PBoxPlayer.Bounds.IntersectsWith(w.Bounds));
if (collision) {
    // adjust location
}

If the wall with which the player has collided is itself a useful piece of information, you can use another variation:

var collidedWith = walls.FirstOrDefault(
    w => Bounds.IntersectsWith(w.Bounds));
if (collidedWith !== null) {
    // collidedWith is the wall we ran into
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top