Hi everyone. So first things first, is that im not no pro programmer. But i do try. Now recently i slapped together my own character controller from ground up, colliders and rigidbody , not made of an actual character controller. And i started plugging out some basic script to move it around. I got this so far, and it moves really nicely, fells good in play mode, but im curious, is this bad? It just seems like a hella lot of IF statements goin on.
PS : Also, notice that value applied to the AddForce method. Thats insane, and it only jumps like… 3 feet.! I havent adjusted anything, except set the weight of the rigidbody to 145 kilo’s. the player object is actually an empty game object, with a capsule collider, and rigidbody attached to it.
Having “lots of if’s” is not necessarily a bad thing, but your script does seem to have more standalone if’s than necessary. For example, take the 2 first if loops. Those 2 loops serve contradictory purposes, which means that they would simply cancel each other out if activated during the same execution of the function. I assume that you don’t want that happening and that you only want one of them to actually activate inside the function. To do that, just turn the second if loop into an else if branch. The same principle applies to the fifth and sixth if loops.
if you strafe right “E” and press the Q key to strafe left, the strafe left cancels out the strafe right , and you begin strafing right. But the same cannot be said for other way around. How would you go about fixing this ?
but I don’t know what unity is doing internaly and if it do the translate job even if all the values are 0… so maybe the first option is safer in terms of raw speed
The Q-check is performed first. If the Q-check fails, then the E-check is performed. If you’re pressing both Q and E at the same time, then the if-else check ends after the Q-check since it will return true. That’s the intended behavior of an if-else check. Now, if you want to give equal priority to both the Q-check and the E-check, then you can keep the 2 standalone if’s that you have and just add the “walkspeed” changes, store the result in a variable and use that for your Translate command. However, -walkspeed + walkspeed will just cancel each other out when both Q and E are pressed at the same time, like before.
7 if-statements is not a lot. if-statements have very little performance cost. I literally have dozens of nested if-statements, sometimes, 5 or 10 levels deep. That’s just pure game logic. Sometimes you need a lot of if-statements and that’s often irreducible beyond combining them into else-if statements or possibly using a switch statement instead.