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 jtemple_unity · Apr 15, 2020 at 11:06 AM · efficiencymoving platformimprovement

Moving Platforms and Efficient Code

Hello, I've created moving platforms in my game that can move left, right, up, or down at the flip of a switch. The code will automatically determine which direction the platform should move based on its moveSpeed, whether it has a distanceX or distanceY value, and if it's in its original or second position.

I have two questions. Firstly, my platform lever uses an OnTriggerStay2D method. It will work the first time I trigger the switch, but I have to move at least one frame before I can trigger the switch again. Is there a better way of doing this?

 public class PlatformLever : MonoBehaviour
 {
 
     [SerializeField] GameObject platform;
 
     public void OnTriggerStay2D(Collider2D collision)
     {
         if (CrossPlatformInputManager.GetButtonDown("Vertical"))
         {
             platform.GetComponent<SwitchablePlatform>().SwitchOn();
         }
     }
 }

Secondly, the platform generally works fine when it's triggered, but I feel like I really brute-forced my way through the code with a lot of if statements and repeated logic. I'm very new to coding so I don't know a lot of best practices or clever tricks yet. I'm wondering if anyone would be kind enough to take a look at my code and either give me some helpful pointers on making it more efficient or pointing me in a direction where I could look for a more efficient way of doing it.

 [DisallowMultipleComponent]
 public class SwitchablePlatform : MonoBehaviour
 {
 
     [Header("Movement Parameters")]
     [SerializeField] float moveSpeed = 1f; // a negative moveSpeed will cause the platform to move backwards
     // the platform will automatically determine which direction to move based on the below two variables
     [SerializeField] float distanceX = 2f;
     [SerializeField] float distanceY = 0f;
 
     [Header("Movement Logic")]
     bool inOriginalPosition = true;
     bool inSecondPosition = false;
     bool isMoving = false;
     Vector2 originalPosition;
     Vector2 secondPosition;
     bool horizontalMovement = false; // when isMoving is true, this will cause the platform to move Horizontally
     bool verticalMovement = false; // when isMoving is true, this will cause the platform to move vertically
 
     // Start is called before the first frame update
     void Start()
     {
         originalPosition = transform.position;
 
         if (distanceX != 0 && distanceY != 0)
         {
             Debug.Log("Platform should only move in one direction");
         }
         else if (distanceX > 0 && distanceY == 0)
         {
             SetHorizontalMovement();
 
         }
         else if (distanceX == 0 && distanceY > 0)
         {
             SetVerticalMovement();
         }
     }
 
     private void SetHorizontalMovement()
     {
         horizontalMovement = true;
         verticalMovement = false;
 
         // the below is used to reinforce the final position of the platform since it won't move to exactly 0 or 0 +- distance
         if (moveSpeed >= 0)
         {
             secondPosition = new Vector2(originalPosition.x + distanceX, originalPosition.y);
         }
         else if (moveSpeed < 0)
         {
             secondPosition = new Vector2(originalPosition.x - distanceX, originalPosition.y);
         }
     }
 
     private void SetVerticalMovement()
     {
         horizontalMovement = false;
         verticalMovement = true;
         
         // the below is used to reinforce the final position of the platform since it won't move to exactly 0 or 0 +- distance
         if (moveSpeed >= 0)
         {
             secondPosition = new Vector2(originalPosition.x, originalPosition.y + distanceY);
         }
         else if (moveSpeed < 0)
         {
             secondPosition = new Vector2(originalPosition.x, originalPosition.y - distanceY);
         }
     }
 
     // Update is called once per frame
     void Update()
     {
         if(isMoving == true)
         {
             Moving();
         }
         else
         {
             return;
         }
         
     }
 
     public void SwitchOn()  // this is called from PlatformLever.cs
     {
         isMoving = true;
     }
 
     private void Moving()
     {
         if (!horizontalMovement && !verticalMovement)
         {
             return;
         }
         else if(horizontalMovement) // determined during Start
         {
             MoveHorizontal();
         }
         else if(verticalMovement) // determined during Start
         {
             MoveVertical();
         }
     }
 
     public void MoveHorizontal()
     {
         float movementXThisFrame = moveSpeed * Time.deltaTime;
         Vector2 currentPosition = transform.position;
         float xPos = originalPosition.x;
         float xCurrent = transform.position.x;
         float movementTracker = xCurrent - xPos; // measure the distance between the current x position and the original x position
 
         // Moving Right
         if (inOriginalPosition) // will move to (roughly) its second position and stop
         {
             if (Mathf.Abs(movementTracker) < distanceX)
             {
                 transform.position = new Vector2(currentPosition.x + movementXThisFrame, originalPosition.y);
             }
             else if (Mathf.Abs(movementTracker) >= distanceX)
             {
                 transform.position = secondPosition; // used to reinforce the final position of the platform since it won't move to exactly 0 or 0 +- distance
                 inOriginalPosition = false;
                 inSecondPosition = true; 
                 isMoving = false;
             }
         }
         else if (inSecondPosition) // will move to (roughly) its original position and stop
         {
             if (movementTracker < 0)
             {
                 transform.position = new Vector2(currentPosition.x - movementXThisFrame, originalPosition.y);
             }
             else if (movementTracker >= 0)
             {
                 transform.position = originalPosition;
                 inOriginalPosition = true;
                 inSecondPosition = false;
                 isMoving = false;
             }
         }
     }
 
     private void MoveVertical()
     {   
         float movementYThisFrame = moveSpeed * Time.deltaTime;
         Vector2 currentPosition = transform.position;
         float yPos = originalPosition.y;
         float yCurrent = transform.position.y;
         float movementTracker = yCurrent - yPos; // measure the distance between the current y position and the original y position
 
         if (inOriginalPosition) // will move to (roughly) its second position and stop
         {
             if (Mathf.Abs(movementTracker) < distanceY)
             {
                 transform.position = new Vector2(originalPosition.x, currentPosition.y + movementYThisFrame);
             }
             else if (Mathf.Abs(movementTracker) >= distanceY)
             {
                 transform.position = secondPosition; // used to reinforce the final position of the platform since it won't move to exactly 0 or 0 +- distance
                 inOriginalPosition = false;
                 inSecondPosition = true;
                 isMoving = false;
             }
         }
         else if (inSecondPosition) // will move to (roughly) its original position and stop
         {
             if (movementTracker < 0)
             {
                 transform.position = new Vector2(originalPosition.x, currentPosition.y - movementYThisFrame);
             }
             else if (movementTracker >= 0)
             {
                 transform.position = originalPosition;
                 inOriginalPosition = true;
                 inSecondPosition = false;
                 isMoving = false;
             }
         }
     }
 }


Thank you very much for taking the time to look at all of this. I really appreciate any help I receive.

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

0 Replies

· Add your reply
  • Sort: 

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

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

What tower defence turret AI approach is best-practice? 1 Answer

Queuing Gameobjects 0 Answers

Does Unity3d Have an Existing Binary Search Class For KeyValuePairs 0 Answers

How to efficiently copy a mesh modified during runtime? 1 Answer

Deleting GameObjects 1 Answer


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