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 /
  • Help Room /
avatar image
0
Question by mateo4632 · Feb 06, 2016 at 02:40 AM · rotationunity 2dbuttonsmovingz-axis

Rotating around z-axis with OnScreen buttons

So I am working on a 2d top down space shooter game for mobile devices. So I started by making it so you can move the ship with the w,a,s,d keys. Now I got it to work but I needed it to be for mobile devices, so I made buttons and got it so the Up and Down arrow work, but the Left and Right arrow don't work. This script "PlayerMovementTouch" is attached to the players ship.

  using UnityEngine;
  using System.Collections;
  
  public class PlayerMovementTouch : MonoBehaviour
  {
      public float Speed = 15;
      public float RotSpeed = 180;
  
      void FixedUpdate()
      {
          move ();
      }
  
      public void move()
      {
          if (GameObject.Find ("CanvasButtons").GetComponent<TouchMovement> ().UpArrow) 
          {
              GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, Speed);
          }
          
          if (GameObject.Find ("CanvasButtons").GetComponent<TouchMovement> ().DownArrow) 
          {
              GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, -Speed);
          }
          
          if (GameObject.Find ("CanvasButtons").GetComponent<TouchMovement> ().LeftArrow) 
          {
              Quaternion rot = transform.rotation;
              float z = rot.eulerAngles.z;
              z -= Input.GetAxis ("Horizontal") * RotSpeed * Time.deltaTime;
              rot = Quaternion.Euler (0, 0, z);
              transform.rotation = rot;
          }
          
          if (GameObject.Find ("CanvasButtons").GetComponent<TouchMovement> ().RightArrow) 
          {
              Quaternion rot = transform.rotation;
              float z = rot.eulerAngles.z;
              z -= Input.GetAxis ("Horizontal") * RotSpeed * Time.deltaTime;
              rot = Quaternion.Euler (0, 0, z);
              transform.rotation = rot;        
          }
      }
  }

Now this script "TouchMovement" is attached to a canvas where all the buttons are.

  using UnityEngine;
  using System.Collections;
  public class TouchMovement : MonoBehaviour 
  {
      public bool UpArrow  = false;
      public bool DownArrow = false; 
      public bool LeftArrow = false;
      public bool RightArrow = false;
      
      public void upArrow()
      {
          StartCoroutine("Uparrow");
          Debug.Log ("UPARROW");
      }
  
      public void downArrow()
      {
          StartCoroutine("Downarrow");
          Debug.Log ("DOWNARROW");
      }
  
      public void leftArrow()
      {
          StartCoroutine("Leftarrow");
          Debug.Log ("LEFTARROW");
      }
      
      public void rightArrow()
      {
          StartCoroutine("Rightarrow");
          Debug.Log ("RIGHTARROW");
      }
       IEnumerator Uparrow()
      {
          UpArrow = true;
          yield return new WaitForSeconds (1);
          UpArrow = false;
      }
  
       IEnumerator Downarrow()
      {
          DownArrow = true;
          yield return new WaitForSeconds (1);
          DownArrow = false;
      }
  
      IEnumerator Leftarrow()
      {
          LeftArrow = true;
          yield return new WaitForSeconds (1);
          LeftArrow = false;
      }
      
      IEnumerator Rightarrow()
      {
          RightArrow = true;
          yield return new WaitForSeconds (1);
          RightArrow = false;
      }
  }

So my problem is I need it when the Left arrow is pushed it moves around the Z axis by it's Rotation Speed Counter Clockwise, while the Right arrow moves Clockwise. Right now the up and down button work but not the Left and Right. Any help would be great!

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
0
Best Answer

Answer by Light997 · Feb 06, 2016 at 10:55 AM

It should work if you get rid of the Input.GetAxis(...) functions. These return 0 unless you are pressing a key on the keyboard (in this case A, D, RightArrow, and LeftArrow), and, as we all learned in school, multiplying something by 0 gives us 0.

Since there is no way to press keys on a touchscreen, I recommend you either:

  1. Get rid of the function entirely

  2. Add Defines in front of it

  3. means:

            if (GameObject.Find ("CanvasButtons").GetComponent<TouchMovement> ().LeftArrow) 
               {
                   Quaternion rot = transform.rotation;
                   float z = rot.eulerAngles.z;
     
     #if UNITY_EDITOR, UNITY_STANDALONE
                   z -= Input.GetAxis ("Horizontal") * RotSpeed * Time.deltaTime;
     #else
                  z -= RotSpeed * Time.deltaTime;
     #endif
                   rot = Quaternion.Euler (0, 0, z);
                   transform.rotation = rot;
               }
    
    

This would allow you to still use the keys in the Editor and on Standalone builds, but the code would not be compiled for mobile. Of course, you have to do the same thing with += for the clockwise turning.

Also, get rid of your GameObject.Find and GetComponent<> functions in FixedUpdate and put them in Start and store them in a variable, otherwise, you will encounter enormous performance issues if you add more buttons, especially on mobile.

What this means is:

     void Start()
     {
         TouchMovement CanvasButtons = GameObject.Find("CanvasButtons").GetComponent<TouchMovement>();
         ...
         ...
         ...
     }

Then later, you can just call the variable from your stored references.

Let me know if this helped you!

Comment
Add comment · Show 5 · 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 mateo4632 · Feb 06, 2016 at 10:31 PM 0
Share

@Light Thank you so much it technically does what i asked for, but some new problems. Now the first one is that it I tested it on my android and it does work, but i want it to rotate when I am holding down the button ins$$anonymous$$d of rotating for 1 second. I know that I have it set up to go for 1 second, but that is because I still have no idea how to do it for when I am holding down the button. Another problem is that when i rotate i want it to move forward based on the way the spaceship is facing. I just realized that i have it moving on the x axis ins$$anonymous$$d of the way the player is facing, which I need to find a way to fix. I hate to ask for more from you but any help would be appreciate. Thanks again!

avatar image Light997 · Feb 06, 2016 at 10:35 PM 0
Share

I'l get back to you as soon as possible, unfortunately, it's quite late now in Central Europe (close to midnight) and I do not have access to a computer. Expect an answer around midday tomorrow, when I am not typing on a tablet that is quite large but still gives me a viewport 3 times smaller than that of my PC. @mateo4632

avatar image mateo4632 · Feb 07, 2016 at 12:23 AM 0
Share

Ok sounds good thank you!

avatar image Light997 mateo4632 · Feb 07, 2016 at 12:53 PM 0
Share

@mateo4632 Try this:

 using UnityEngine;
 using System.Collections;
 
 public class Player$$anonymous$$ovementTouch : $$anonymous$$onoBehaviour
 {
     public float Speed = 15;
     public float RotSpeed = 180;
 
     private Rigidbody2D playerRigidbody;
     private Touch$$anonymous$$ovement touch$$anonymous$$ovement;
 
     void Awake()
     {
         playerRigidbody = GetComponent<Rigidbody2D>();
         touch$$anonymous$$ovement = GameObject.Find("CanvasButtons").GetComponent<Touch$$anonymous$$ovement>();
     }
 
     void FixedUpdate()
     {
         $$anonymous$$ove();
     }
 
     public void $$anonymous$$ove()
     {
         if (touch$$anonymous$$ovement.UpArrow)
         {
             playerRigidbody.AddForce(transform.up * Speed);
         }
 
         if (touch$$anonymous$$ovement.DownArrow)
         {
             playerRigidbody.AddForce(transform.up * -Speed);
         }
 
         if (touch$$anonymous$$ovement.LeftArrow)
         {
             Quaternion rot = transform.rotation;
             float z = rot.eulerAngles.z;
 
 #if UNITY_EDITOR || UNITY_STANDALONE
             z -= Input.GetAxis("Horizontal") * RotSpeed * Time.deltaTime;
 #else
               z -= RotSpeed * Time.deltaTime;
 #endif
             rot = Quaternion.Euler(0, 0, z);
             transform.rotation = rot;
         }
 
         if (touch$$anonymous$$ovement.RightArrow)
         {
             Quaternion rot = transform.rotation;
             float z = rot.eulerAngles.z;
 
 #if UNITY_EDITOR || UNITY_STANDALONE
             z += Input.GetAxis("Horizontal") * RotSpeed * Time.deltaTime;
 #else
               z += RotSpeed * Time.deltaTime;
 #endif
             rot = Quaternion.Euler(0, 0, z);
             transform.rotation = rot;
         }
     }
 }

This should move the player dependent on their rotation with transform.up.

For the holding the button problem, look at this post:

Unity Answers - $$anonymous$$aking a hold button for the new UI

avatar image mateo4632 · Feb 07, 2016 at 04:32 PM 0
Share

Thank you so much @Light you've helped me so much and I can properly fly around in my game on my mobile device. You saved from hours of trying to figure it out thanks again!

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

47 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

Related Questions

Unity 2D - Rotating the controls themselves 0 Answers

How to make a cube rotate while moving? 1 Answer

Limiting gameObjects rotation on Zaxis giving wierd results 1 Answer

Rotate on z axis while move up and down 0 Answers

Car Rotation when pressing buttons 0 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