• 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 Got1000IQ · Jan 22 at 12:51 PM · 2d platformer

help me make this 2d script more efficient

ok so I made this 2d platformer script, its fully functional but I'd just like to know if I can shorten it, or cut out some variables because in its current state its kinda messy and hard to navigate, also leave some opinion and useful tips for future scripts :)

Literally copy paste:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class PlayerBehaviour : MonoBehaviour
 {
     public KeyCode keyUp = KeyCode.W;
     public KeyCode keyLeft = KeyCode.A;
     public KeyCode keyRight = KeyCode.D;
     float movingLeft = 0;
     float movingRight = 0;
 
     
 
     float horMovement = 0f;
     
     float horMovementAcceleration = 2f;
     public float horMovementMaxSpeed = 6f;
     float horMovementDeceleration = -0.5f;
     float horFace = 1;
     
     public Rigidbody2D rb2d;
     public float jumpStrenght = 10;
     public float jumpDeceleration = 0.5f;
     float jump = 0;
     bool isGrounded = false;
     public Transform GroundCheck1; // Put the prefab of the ground here
     public LayerMask groundLayer; // Insert the layer here.
 
 
     // Start is called before the first frame update
     void Start()
     {
         rb2d = GetComponent<Rigidbody2D>();
     }
 
     // Update is called once per frame
     void Update()
     {
         isGrounded = Physics2D.OverlapCircle(GroundCheck1.position, 0.15f, groundLayer);
         if (Input.GetKeyDown(keyUp) && isGrounded)
         {
             Jump();
         }
 
         Debug.Log("horMovement:"+horMovement);
 
 
         if (Input.GetKey(keyRight)) { movingRight = 1f; } else { movingRight = 0f; }
         if (Input.GetKey(keyLeft)) { movingLeft = 1f; } else { movingLeft = 0f; }
         
         
         //set horFace
         if ((movingLeft * -1) + movingRight != 0)
         {
             horFace = (movingLeft * -1) + movingRight;
             Debug.Log("horFace:" + horFace);
         }
 
         if (horMovement > .5f || horMovement < -.5f)
         {
             if (!Input.GetKey(keyRight) && !Input.GetKey(keyLeft))
             {
                 Decelerate();
             }
         }
         else
         {
             horMovement = 0;
         }
 
 
 
         //set max speed
         if (Input.GetKey(keyRight) || Input.GetKey(keyLeft))
         {
             if (horFace == 1)
             {
                 if (horMovement < horMovementMaxSpeed * 1)
                 {
                     Accelerate();
                 }
                 else
                 {
                     horMovement = horMovementMaxSpeed * 1;
                 }
 
             }
             else
             {
                 if (horMovement > horMovementMaxSpeed * -1)
                 {
                     Accelerate();
                 }
                 else
                 {
                     horMovement = horMovementMaxSpeed * -1;
                 }
             }
         }
 
 
 
 
     }
 
     void Accelerate()
     {
         Debug.Log("Accelerating...");
         horMovement += horMovementAcceleration * horFace;
     }
 
     void Decelerate()
     {
         Debug.Log("Decelerating...");
         horMovement += horFace * horMovementDeceleration;
     }
 
     void FixedUpdate()
     {
         rb2d.velocity = new Vector2(horMovement, jump);
         if (jump >= jumpStrenght*-1) { jump -= jumpDeceleration; }
     }
 
     void Jump()
     {
         jump = jumpStrenght*2;
     }
 }
 

thanks in advance :)

Comment
Add comment · Show 2
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 Got1000IQ · Jan 22 at 12:55 PM 0
Share

oh and also, I want to use slopes with this code, but currently the player always slides down the slopes when standing still, plus he has a hard time walking up slopes, so if anyone got a solution for how I can make the slopes less tedious pls help out!

avatar image FlightOfOne · Jan 23 at 04:53 PM 0
Share

I am going to assume you are asking for optimization tips.

Your code does not look too bad.

Watch this video: https://www.youtube.com/watch?v=_wxitgdx-UI

Before you check performance(e.g. profiler) or build just be sure to comment out all the Debug.Log()s. or you will see big spikes.

  //Create this vector out side of the fixed update, that way you won't be constructing this struct on every frame.
 
     Vector2 movementVector=new Vector2();
     
     
     void FixedUpdate()
          {
           movementVector.x=horMovement;
            movementVector.y=jump
              rb2d.velocity = movementVector;
              if (jump >= jumpStrenght*-1) { jump -= jumpDeceleration; }
          }





1 Reply

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

Answer by VincentLagerros · Jan 22 at 05:22 PM

I would do something like this (have not tried if it works):

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class PlayerBehaviour : MonoBehaviour
 {
     [Tooltip("The Jump key")] public KeyCode keyUp = KeyCode.W;
     [Tooltip("Walk left")] public KeyCode keyLeft = KeyCode.A;
     [Tooltip("Walk right")] public KeyCode keyRight = KeyCode.D;
     [Tooltip("How fast the character walks")] public float walkSpeed = 10;
     [Tooltip("The maximum walking speed")] public float maxWalkSpeed = 10;
     [Tooltip("How high the character jumps")] public float jumpStrenght = 10;
 
     public Rigidbody2D rb2d;
     bool isGrounded = false;
 
     public string groundTag = "ground";
 
     private void OnCollisionEnter2D(Collision2D col)
     {
         if (col.gameObject.tag == groundTag) {
             isGrounded = true;
         }
     }
 
     private void OnCollisionExit2D(Collision2D col)
     {
         if (col.gameObject.tag == groundTag) {
             isGrounded = false;
         }
     }
 
     void Jump()
     {
         rb2d.AddForce(new Vector2(0, jumpStrenght));
     }
 
     // Start is called before the first frame update
     void Start()
     {
         rb2d = GetComponent<Rigidbody2D>();
     }
 
     // Update is called once per frame
     void Update()
     {
         if (Input.GetKeyDown(keyUp) && isGrounded) {
             Jump();
         }
 
         float horSpeed = 0;
         if (Input.GetKey(keyRight)) { horSpeed += walkSpeed; }
         if (Input.GetKey(keyLeft)) { horSpeed -= walkSpeed; }
         rb2d.AddForce(new Vector2(horSpeed, 0));
         if(Mathf.Abs(rb2d.velocity.x) > maxWalkSpeed ) { // max velocity on x-axis
             rb2d.velocity = new Vector2( maxWalkSpeed * (Mathf.Abs(rb2d.velocity.x)/ rb2d.velocity.x), rb2d.velocity.y);
         }
     }
 }


Comment
Add comment · Show 3 · 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 Got1000IQ · Jan 23 at 04:17 PM 0
Share

no unfortunately it didn't work ;( but hey atleast now I know I can do that cool tooltip thingie so it wasn't all for nothing :p

avatar image VincentLagerros Got1000IQ · Jan 23 at 04:55 PM 0
Share

Just tried it, and it works for me. A few things you might have missed: 1. Tag the ground to a "ground" tag (just as it is the same as the variable groundTag it should work) 2. Change jump to something like 500, or you will not see any change

And you can also use [Header("Movement")] before a public variable to make a bold "Movement" text show up before that variable in the inspector

avatar image Got1000IQ VincentLagerros · Jan 24 at 03:08 PM 0
Share

ah yea now it works xD, thank you very much both for helping me out but also for the tooltip and header tips :P

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.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

101 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 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

Generating 2D Level Through Arrays 0 Answers

Changing animation when moving horizontally without flipping sprite 0 Answers

Particle System for Death effect 1 Answer

Adding knockback to a 2D game (in C#) 2 Answers

Blur 2d Sprite 0 Answers

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges