Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by ragefordragons · Feb 23, 2018 at 01:21 AM · player movementfixorganizationtipscleanup

Tips on Cleaning up my player controller

So I am creating a somewhat ambitious platformer/hack and slash game, and it is going pretty well. However, while I have decent C# knowledge, I am no expert and am not very expirienced. This is my player controller, and I was just wondering if anyone has tips on how to clean it up and make it better. Its pretty messy right now, but there are a few things that need fixing: 1. making it so that when it gets horizontal inputs it runs the running animation instead of having to make a seperate if statemnt(with flipping too) 2. Making it so that you cant wall jump, as touching walls right now resets the jump, and also if you walk against them it bugs the character out and can break physics. 3. Maybe make it expandablfe for custom controlls later on? If you have any Ideas on how to acheive these, just tell me your ideas, I would love to hear some!

using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Sprites;

public class playerController : MonoBehaviour {

 // initialize all varaibles
 private float speed = 8;
 public GameObject hitbox;
 public static float damage;
 public static float coins = 0;
 public static float LucaHP;
 public static float LucaSP;
 public bool grounded;
 private float jumpspd = 12;
 public Animator anim;
 public bool isRunning;
 public SpriteRenderer ren;
 public bool canDash = true;
   



 // Use this for initialization
 void Start()
 {

     anim = gameObject.GetComponent<Animator>();
     anim.SetBool("isRunning", false);
     anim.SetBool("dashing", false);

     canDash = true;
 }

 // Update is called once per frame
 void Update()
 {


     playermove();

    



 }

 private void OnTriggerEnter2D(Collider2D col)
 {
     if (col.gameObject.tag == "ground")
     {
         grounded = true;
     }
 }



 void playermove()
 {
     float axixX = Input.GetAxis("Horizontal");

     transform.Translate(new Vector3(axixX, 0) * Time.deltaTime * speed);

     if (Input.GetButton("Horizontal"))
     {
         isRunning = true;

     }
     else
     {
         isRunning = false;
     }
     anim.SetBool("isRunning", isRunning);

     if (Input.GetKeyDown(KeyCode.A))
     {
         ren.flipX = true;
     }
     if (Input.GetKeyDown(KeyCode.D))
     {
         ren.flipX = false;
     }

     if (Input.GetKeyDown(KeyCode.Space))
     {
         if (grounded == true)
         {
             GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpspd);
             grounded = false;

         }
     }

     if (Input.GetKeyDown(KeyCode.LeftShift))
     {

         StartCoroutine(dash());
     }
 }


 IEnumerator dash()
 {
     if (canDash == true)
     {
         canDash = false;
         anim.SetBool("dashing", true);
         if (ren.flipX == true)
     {
         GetComponent<Rigidbody2D>().velocity = new Vector2(-jumpspd / 2, GetComponent<Rigidbody2D>().velocity.y);

     }
     else
     {

         GetComponent<Rigidbody2D>().velocity = new Vector2(jumpspd / 2, GetComponent<Rigidbody2D>().velocity.y);

     }
     yield return new WaitForSeconds(0.5f);
         anim.SetBool("dashing", false);
         canDash = true;
     }
 }


}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Xarbrough · Feb 23, 2018 at 01:59 AM

So the first thing I would advise is, to stick to a coding style and keep clean form:

 using UnityEngine;
 using System.Collections;
 
 public class PlayerController : MonoBehaviour
 {
     [Tooltip("The maximum horizontal movement speed in units per second.")]
     public float moveSpeed = 8;
 
     [Tooltip("The maximum vertical jump speed in units per second.")]
     public float jumpSpeed = 12;
 
     public SpriteRenderer spriteRenderer;
 
     Animator animator;
     bool grounded;
     bool isRunning;
     bool canDash;
 
     void Start()
     {
         animator = GetComponent<Animator>();
         canDash = true;
     }
 
     void OnTriggerEnter2D(Collider2D other)
     {
         if (other.CompareTag("ground"))
         {
             grounded = true;
         }
     }
 
     void Update()
     {
         float horizontalInput = GetInput();
         Move(horizontalInput);
         UpdateAnimator(horizontalInput);
 
         HandleFlip();
         HandleJump();
         HandleDash();
     }
 
     float GetInput()
     {
         return Input.GetAxis("Horizontal");
     }
 
     void Move(float input)
     {
         transform.Translate(input * moveSpeed * Time.deltaTime, 0f, 0f);
     }
 
     void UpdateAnimator(float input)
     {
         bool tmpIsRunning = input > 0.001f;// Some small value close to zero.
 
         if (isRunning != tmpIsRunning) // Only update the animator, if we need to.
         {
             isRunning = tmpIsRunning;
             animator.SetBool("isRunning", isRunning);
         }
     }
 
     void HandleFlip()
     {
         if (Input.GetKeyDown(KeyCode.A))
         {
             spriteRenderer.flipX = true;
         }
         if (Input.GetKeyDown(KeyCode.D))
         {
             spriteRenderer.flipX = false;
         }
     }
 
     void HandleJump()
     {
         if (Input.GetKeyDown(KeyCode.Space))
         {
             if (grounded == true)
             {
                 GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jumpSpeed);
                 grounded = false;
             }
         }
     }
 
     void HandleDash()
     {
         if (Input.GetKeyDown(KeyCode.LeftShift))
         {
             StartCoroutine(PerformDash());
         }
     }
 
     IEnumerator PerformDash()
     {
         if (canDash == true)
         {
             canDash = false;
             animator.SetBool("dashing", true);
             if (spriteRenderer.flipX == true)
             {
                 GetComponent<Rigidbody2D>().velocity = new Vector2(-jumpSpeed / 2, GetComponent<Rigidbody2D>().velocity.y);
             }
             else
             {
                 GetComponent<Rigidbody2D>().velocity = new Vector2(jumpSpeed / 2, GetComponent<Rigidbody2D>().velocity.y);
             }
             yield return new WaitForSeconds(0.5f);
             animator.SetBool("dashing", false);
             canDash = true;
         }
     }
 }
 

It's not about changing any of the logic yet, but a clean form is one of the most important aspects because code must be optimized for human reading since you are going to read more code than do anything else (at least you should be reading and thinking a lot :p). Try to think of good variable names, comment what you want them to do. This helps to create a good mental model of what you want to achieve.

Next, structure your code so it is easy to read. Suddenly you may notice, that there are unused variables or things you could move (I know you want those for future features, but just as an example). Separate public inspector-tweakable variables from private state tracking. Think about if you want references to be populated via the inspector or by GetComponent. Best stick to one idiom. Separate logical pieces into functions with one goal like "here I move the player, here I update the animator". This helps track down bugs (and has lots of benefits later on).

Remove those static variables. They look like you have problems communicating between scripts (google "script communication" for some help), but these variables are either settings or state of the class, therefore belong to the instance. Statics are shared by all scripts of the same type and should be used sparingly (e.g. a count of Zombie instances which gets updated in Start).

Writing player controllers has been discussed on the Forums and here on Answers a lot, there are also many practical tutorials (from the official Learn site, for example), so I'm not gonna propose anything functional, especially because you asked so many questions at the same time. Each one is a topic of its own, and time well spent on. ;)

My general advice would be to separate the responsibilities of your scripts. "PlayerController" is already a bad name, because that implies so many sub-tasks. To me, a PlayerController handles only movement. You can argue that animations are linked so close, that it makes sense to also update them from the same script. However, damage, coins, and hp definitely belong in separate scripts like "Weapon", "CoinTracker", and "PlayerHealth". This is not only a generally proven programming paradigm but also helps to focus on specific problems. You don't want to tackle all things at once, just get one thing going after the other.

Maybe post your progress, someone may have input on specific issues or give more tips. Btw I'm not saying anything about performance here because it's not the right time to optimize; save that for later.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ragefordragons · Feb 23, 2018 at 02:39 AM 0
Share

Hey thanks! Its really in depth and helpful. I modified my script similarly to this, and will certainly take into account what you said as I go.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

75 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Organize Inspector Better? 1 Answer

Having a lot of trouble with 2d movement 1 Answer

NavMeshAgent Not Working? 1 Answer

joystick script not working need some help ! 0 Answers

how to stop player movemnt when there is something near him 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges