Advertisement

Need Help Declaring Variables

Started by June 05, 2015 10:55 PM
9 comments, last by Oberon_Command 9 years, 8 months ago

OK I wrote this code but I don't know why it doesn't work.


It doesn't work because you're using '=' instead of '==' to test for equality. Your compiler should have put up a warning about this. In C++, '=' always means assignment. So when you say "if (PlayerRect.x = EnemyRect.x) ", that will actually set PlayerRect.x to EnemyRect.x. Then the expression in the 'if' statement will evaluate to whatever EnemyRect.x is, which in C++ gets converted to 'true' if it isn't 0 because that's how C did it and C++ preserves a lot of things from C for backwards compatibility. This is one reason why C++ is not always recommended for beginners.

In short: change all of your '=' to '==' in the if statements you wrote.
Side note: in the future, please put code that you post in {source}{/source} tags (replace the {} with []).

But After I detect that there is intersection , what will I do ??


Do whatever you want to do when a collision is detected. That's the purpose of a collision system - to notify the rest of the game that a collision has occurred.

HasIntersection just tells if there is an intersection or not and there is now way that I can check the last position of the first rect before intersection so I can prevent it from intersection.


Why don't you just preserve the last position of the rectangles, too?


How ?


It depends on how you're storing your collision data in the first place. What I suggest is this:

- When you go to move something, figure out what the rectangles of your objects will be after the movement. Don't actually move them just yet, just figure out where they're going to go.
- Do collision detection on the new rectangles to see if moving would cause any of your objects to collide.
- If any of your objects have collisions, either don't move them, or figure out how to move them just far enough that they touch. For objects that won't collide with anything, just move them as usual.
- If any other part of the game needs to know that collisions occurred, tell those parts of the game about the collisions that occurred. How you do this is entirely up to you and depends on the architecture of your program, so I can't give sound advice without knowing more about how you're doing things.

This topic is closed to new replies.

Advertisement