For the past 12 hours I’ve been trying “all” different methods I can think of, in order to make two rectangles intersect/test collision correctly in XNA (4.0).
I have three classes (just example names):
- Game1.cs
- Player.cs
- Man.cs
In Game1 I load the content like this:
// In the beginning of Game1:
Player player;
Man man;
// LoadContent:
man = new Man(Content.Load<Texture2D>("ManImage"), new Rectangle(440, 310, 150, 98));
player = new Player(Content.Load<Texture2D>("playerSheet"), new Vector2(40, 420), 50, 44);
However, I want to check for collision between man and player, but I don’t understand how to “join” those two classes to be able to do an if(intersects) in Game1 (if that’s the place to do it).
The player rectangle looks like this:
playerRect = new Rectangle(currentFrame * frameWidth, 0, frameWidth, frameHeight);
Have I just gone completely “code blind” here, or what? Anyone able to help me out with this, motivation went down after 12 hours of collision testing.
You could, for both of the classes, add a property
then, in the relevant constructors, you’d need to initiate this property
You don’t need to worry about what frame you’re displaying, since this is related to the source rectangle, not to the destination rectangle (which is what you need to test for collisions).
Then you can test for these collisions easily
Of course, you’d need to take care to update these rectangles any time you change the positions (or widths and heights if those are changeable)
Slight edit (or a better version)
If you would like to position Man and Player easily without having to worry about how their rectangles are updated, you could set it up like this:
Here I’ve given you example of how you could make use of property accessors to dynamically generate your relevant rectangles!
You use
PositionRectangleto determine where your player (or man) will be located on screen, and you useSourceRectangleto determine which part of the texture you’re gonna draw.Also, if your man and player widths and heights aren’t going to change then you should set their
setaccessors toprivate.When you need to change the locations, you just set their position property
and your collisions and draw logic will automatically use the new rectangles without any further intervention!
Hope you like it!
Edit2
Relating to source rectangle being public, you only need that if you’re drawing these from outside (i.e.
Game1callsspriteBatch.Draw(player.Texture, player.PositionRectangle, player.SourceRectangle, Color.White);).If you’re drawing it like in the example (from the inside), you could just scrap the whole
public Recangle SourceRectangle{...}thing and just use that rectangle directly in the draw: