Thread: Better way to do this?

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    36

    Better way to do this?

    I know there's a term for this - not sure what it is. Anyway, I have a 2d tile engine for a game. In the tile data, there is a single number for the collision data. Each quadrant of the tile has it's own collision detection, so all the flags are represented as one number.

    Maybe it would be easier to understand if I pasted my code:
    Code:
    stringstream stream(buffer);
    			int collision;
    			//converts the hex value into an int
    			stream>>hex>>collision;
    
    			//if collision is 0 then it doesn't collide with anything
    			if (collision>0)
    			{
    				if (collision>=8)
    				{
    					collision-=8;
    					collideBR=true;
    				}
    				if (collision>=4)
    				{
    					collision-=4;
    					collideBL=true;
    				}
    				if (collision>=2)
    				{
    					collision-=2;
    					collideTR=true;
    				}
    				if (collision>=1)
    				{
    					collision-=1;
    					collideTL=true;
    				}
    			}
    This works fine, does what I need. It just seems sloppy to me. The collideTL BL etc stands for top right, bottom left, etc. Is there a cleaner way to do this?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Code:
    collideBR = ( collision & 0x8 ) != 0;
    collideBL = ( collision & 0x4 ) != 0;
    and so on for the other two.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2005
    Posts
    36
    Thanks! That is what I was looking for. However, I noticed that I can achieve the same result without having the "!= 0".

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    However, I noticed that I can achieve the same result without having the "!= 0".
    That is because non-zero integers are converted to true when cast to bool, and zero is cast to false. The "!= 0" is probably good to keep since it clarifies that you are assigning a boolean, not integral, value.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed