Better way to do this?

This is a discussion on Better way to do this? within the C++ Programming forums, part of the General Programming Boards category; I know there's a term for this - not sure what it is. Anyway, I have a 2d tile engine ...

  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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,663
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  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
    21,910
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21