View Full Version : Beginner needs help
davidtidwell86
May 26th, 2009, 12:26 AM
Hello, I have the following statement in my code:
if( spriteSpeed > 0 ) {
if( spriteSpeed > spriteMaxSpeed )
{
spriteSpeed = spriteMaxSpeed;
}
} else if ( spriteSpeed < 0 ) {
if( spriteSpeed < -( spriteMaxSpeed ))
{
spriteSpeed = -( spriteMaxSpeed );
}
}
It works fine, but my question is whether or not there's a more 'professional' way to rewrite this. It seems inefficient to treat the positive and negative signage separately. Thanks so much for your help!
Shaedo
May 26th, 2009, 04:41 AM
assuming you are not using imaginary numbers then why not:
if( spriteSpeed > spriteMaxSpeed )
{
spriteSpeed = spriteMaxSpeed;
}
if( spriteSpeed < -( spriteMaxSpeed ))
{
spriteSpeed = -( spriteMaxSpeed );
}
davidtidwell86
May 26th, 2009, 11:17 PM
Thanks for your reply. As long as the code seems to be efficient, I guess that's all that matters. I was just scared I was making it more complicated than it had to be. Thanks again! :)
milkmit
May 26th, 2009, 11:37 PM
If you want to make it a bit more compact (at the expense of readability, somewhat), this could work as well:
spriteSpeed > spriteMaxSpeed ? spriteSpeed = spriteMaxSpeed : null;
spriteSpeed < -(spriteMaxSpeed) ? spriteSpeed = -(spriteMaxSpeed) : null;
I don't know if "null" is the best thing to use to return nothing ("void" works as well, but seems even less proper), but it works fine in my testing.
And if you haven't dealt with those sort of conditionals before, they basically work like this:
(evaluate statement) ? (do this if true) : (do this if false)
So if the value of the first part before the ? is true, it will execute the first code right after the ? but before the :. If it's false, it will execute the code after the :.
I'm not sure how they compare when it comes to speed, but they're a quick way to reduce code size for simple if/thens.
Powered by vBulletin® Version 4.1.10 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.