- Home /
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;
}
}
}
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.
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
Follow this Question
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