- Home /
Make code shorter/prettier?
Hello! I have a lot of codes I wrote that work just fine but I think they're not "optimized" or at least they look like the easy but long way around solving a problem.
Right now I have a slide script, it works, but it's not "good looking". Basically, I want a shorter and smarter way to write it. My code is below, I was wondering if there is a way to make it shorter. [cc is a Charactercontrller, Bobbing.camOffset is the cameras localPosition on the y-axis as a child of the player.]
Code is:
void DoSlide()
{
if (cc.height > 1f)
{
cc.height -= Time.deltaTime * 2f * slideCrouchSpeed;
}
if (cc.center.y > -0.5f)
{
cc.center -= new Vector3(0f, 1f, 0f) * Time.deltaTime * slideCrouchSpeed;
}
if (Bobbing.camOffset > -0.15f)
{
Bobbing.camOffset -= Time.deltaTime * 2f * slideCrouchSpeed;
}
if (moveVector.magnitude > 0f) { movementSpeed = slidingSpeedThingy; }
if (slidingSpeedThingy > walkingSpeed)
{
slidingSpeedThingy -= Time.deltaTime * slideSpeedFallOff;
}
}
void StopSlide()
{
if (cc.height < 2f)
{
cc.height += Time.deltaTime * 2f * slideStandSpeed;
}
if (cc.center.y < 0f)
{
cc.center += new Vector3(0f, 1f, 0f) * Time.deltaTime * slideStandSpeed;
}
if (Bobbing.camOffset < 0.75f)
{
Bobbing.camOffset += Time.deltaTime * 2f * slideStandSpeed;
}
slidingSpeedThingy = slidingSpeed;
movementSpeed = walkingSpeed;
}
Thank you so much!
Answer by eneIr · Jun 18, 2021 at 02:50 PM
For shortening you script, instead of using new Vector3(0f, 1f, 0f), you can use Vector3.up, and your if() statements only have one line of code so you can remove the {} brackets. E.g:
if (cc.height > 1f)
{
cc.height -= Time.deltaTime * 2f * slideCrouchSpeed;
}
change to:
if (cc.height > 1f)
cc.height -= Time.deltaTime * 2f * slideCrouchSpeed;
For performance optimization, the moveVector.magnitude can be changed to moveVector.sqrMagnitude, I learned this from a tutorial video from Brackeys. That's all I can think of.
If I remove the brackets, does it impact preformance? Also, sqrMagnitude doesn't return the same value as magnitude? I just tried it and it broke the script?
It just makes the script shorter. And use the sqrMagnitude only when you compare it to 0 like in this part: "if (moveVector.magnitude > 0f)", if you use it to compare it to other positive numbers, just square those numbers. However, if you want to use the vector magnitude to move or something, just use the magnitude for simplicity.
Your answer
Follow this Question
Related Questions
Cinemachine rotate behind player sooner when walking towards the camera 0 Answers
Emission blinking script 1 Answer
Memory game in 3d space 1 Answer
Tracking changes in velocity 1 Answer