• 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
4
Question by VegasD78 · Jan 26, 2014 at 05:51 AM · accelerometer

Use Accelerometer for Roll-a-ball Movement

I'd like to use the accelerometer to control the roll-a-ball from t$$anonymous$$s awesome tutorial on my iPhone and am having some trouble finding out how to do so. I've been able to get it to work along one axis (x) somewhat properly, but when I enable the y axis the ball jumps up in the air rather than rolls north / south (phone is held in landscape mode with home button on right).

I've tried adding a z axis to the script but it didn't seem to do anyt$$anonymous$$ng at all. Can you please assist? I'm using C# and here's the full script below:

 using UnityEngine;
 using System.Collections;
 
 public class PlayerController : MonoBehaviour 
 {
     public float speed;
     public float force = 11.0f; //used for accelerometer controls
 
     void FixedUpdate ()
     {
     
     //are we using a computer as opposed to a mobile device with an accelerometer?
     if(SystemInfo.deviceType == DeviceType.Desktop)
         {
         //start of movement code from rollerball tutorial
         //used for desktop movement
         float moveHorizontal = Input.GetAxis("Horizontal");
         float moveVertical = Input.GetAxis("Vertical");
         
         Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
         
         rigidbody.AddForce(movement * speed * Time.deltaTime);
         //end of movement code from rollerball tutorial
         }
         //or are we on mobile with an accelerometer?
         else
         {
             //start accelerometer code here
             Vector3 dir = Vector3.zero;
             dir.x = Input.acceleration.x;
             //dir.y = Input.acceleration.y;
             Physics.gravity = dir * force;
         }
     
     }
 
     void OnTriggerEnter(Collider other) 
     {
         if(other.gameObject.tag == "Pickup")
         {
             other.gameObject.SetActive(false);
         }
     }
 }


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 Big_T · Oct 04, 2014 at 11:03 AM 0
Share

I'm still new to using Unity and the forums here but this code I think would work for me and my problem as well. Is it okay for me to use it in my project also? I do not want to use something without permission. I'm just trying to figure out the etiquette of the forums still.

avatar image D3nkianma · May 18, 2017 at 04:29 AM 0
Share

Im curious as to how any of these worked for anyone but maybe I'm missing something completely(I am very new to Unity) But every solution here either threw a billion compiler errors and the ones that worked, once loaded on my android device the ball literally flew across the screen at the slightest movement and bounced outside the box into nothingness.

8 Replies

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

Answer by Uniblack · Feb 16, 2015 at 12:13 AM

T$$anonymous$$s one works for me:

 using UnityEngine;
 using System.Collections;
 
 public class PlayerController : MonoBehaviour 
 {
     // Using same speed reference in both, desktop and other devices
     public float speed =1000;
 
     void Main ()
         {
                 // Preventing mobile devices going in to sleep mode 
                 //(actual problem if only accelerometer input is used)
                 Screen.sleepTimeout = SleepTimeout.NeverSleep;
         }
 
     void Update()
         {
          
         if (SystemInfo.deviceType == DeviceType.Desktop) 
         {
             // Exit condition for Desktop devices
             if (Input.GetKey("escape"))
                 Application.Quit();
         }
         else
         {
             // Exit condition for mobile devices
             if (Input.GetKeyDown(KeyCode.Escape))
                 Application.Quit();            
         }
         
         
 
         }
     
     
     void FixedUpdate ()
         {
             if (SystemInfo.deviceType == DeviceType.Desktop) 
             { 
                     // Player movement in desktop devices

                 // Definition of force vector X and Y components
                 float moveHorizontal = Input.GetAxis("Horizontal");
                 float moveVertical = Input.GetAxis("Vertical");
                 // Building of force vector
                 Vector3 movement = new Vector3 (moveHorizontal,0.0f,moveVertical);
                 // Adding force to rigidbody
                 rigidbody.AddForce(movement * speed * Time.deltaTime);
             }
             else
             {
                     // Player movement in mobile devices

                 // Building of force vector 
                 Vector3 movement = new Vector3 (Input.acceleration.x, 0.0f, Input.acceleration.y);
                 // Adding force to rigidbody
                 rigidbody.AddForce(movement * speed * Time.deltaTime);
             }
 
 
         }
 
         
 }

Comment
Add comment · Show 4 · 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 dangalg · Sep 18, 2015 at 08:15 AM 0
Share

Best answer

avatar image Deathcrew · Nov 14, 2016 at 12:07 AM 0
Share

work perfectly ... tnxxx

avatar image atrajano · Jun 12, 2017 at 12:20 PM 1
Share

Why is Time.deltaTime needed?

avatar image HanSoloYolo · Oct 25, 2017 at 08:14 PM 0
Share

I had to use GetComponent(); instead, but this really works! THANK YOU SO MUCH FOR SHARING THE SOLUTION!

*Tip: You can change rigid.AddForce to transform.Translate in order to have the object move without rolling!

 using UnityEngine;
 using System.Collections;
 
 public class PlayerController : MonoBehaviour
 {
     // Using same speed reference in both, desktop and other devices
     public float speed = 1000;
     private Rigidbody rigid;
 
     private void Start()
     {
         rigid = GetComponent<Rigidbody>();
     }
 
     void Main()
     {
         // Preventing mobile devices going in to sleep mode 
         //(actual problem if only accelerometer input is used)
         Screen.sleepTimeout = SleepTimeout.NeverSleep;
     }
 
     void Update()
     {
 
         if (SystemInfo.deviceType == DeviceType.Desktop)
         {
             // Exit condition for Desktop devices
             if (Input.GetKey("escape"))
                 Application.Quit();
         }
         else
         {
             // Exit condition for mobile devices
             if (Input.GetKeyDown(KeyCode.Escape))
                 Application.Quit();
         }
 
 
 
     }
 
 
     void FixedUpdate()
     {
         if (SystemInfo.deviceType == DeviceType.Desktop)
         {
             // Player movement in desktop devices
             // Definition of force vector X and Y components
             float moveHorizontal = Input.GetAxis("Horizontal");
             float moveVertical = Input.GetAxis("Vertical");
             // Building of force vector
             Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
             // Adding force to rigidbody
             rigid.AddForce(movement * speed * Time.deltaTime);
         }
         else
         {
             // Player movement in mobile devices
             // Building of force vector 
             Vector3 movement = new Vector3(Input.acceleration.x, 0.0f, Input.acceleration.y);
             // Adding force to rigidbody
             rigid.AddForce(movement * speed * Time.deltaTime);
         }
 
 
     }
 
 
 }


Searched the internet for 3 days looking for a solution. Thank you so very much! Sincerest Gratitude!

*THIS CODE WORKS!

avatar image
8

Answer by oskario2 · Feb 02, 2014 at 06:18 PM

I have been looking the same and I found a code that works, replace it for your code on the accelerometer code here section. speedAc is a float that I give a value of 10 and works fine.

 curAc = Vector3.Lerp(curAc, Input.acceleration-zeroAc, Time.deltaTime/smooth);
 GetAxisV = Mathf.Clamp(curAc.y * sensV, -1, 1);
 GetAxisH = Mathf.Clamp(curAc.x * sensH, -1, 1);
 // now use GetAxisV and GetAxisH instead of Input.GetAxis vertical and horizontal
 // If the horizontal and vertical directions are swapped, swap curAc.y and curAc.x
 // in the above equations. If some axis is going in the wrong direction, invert the
 // signal (use -curAc.x or -curAc.y)
             
 Vector3 movement = new Vector3 (GetAxisH, 0.0f, GetAxisV);
 rigidbody.AddForce(movement * speedAc);


Even I would appreciate some tutorial/examples regarding different inputs from mobile devices.

Comment
Add comment · Show 2 · 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 Byroman · Mar 01, 2014 at 04:30 AM 0
Share

^Hey I can't up vote your answer because of my "reputation" but I can confirm that your code works. I've been trying to get an accelerometer to curve a ball for a while now and this is the first time I've gotten it to work, so thanks!

avatar image robertbu · Mar 01, 2014 at 04:32 AM 0
Share

@Byroman - If your questions is answered, please click on the checkmark to close the question out. It will also give @oskario2 some Karma. Thanks.

avatar image
1

Answer by Byroman · Mar 01, 2014 at 11:06 PM

Sure, but I'm actually wondering what zeroAc is. Because I don't subtract Input.acceleration by it in my version and it causes the accelerometer to be way too sensitive.

Comment
Add comment · Show 2 · 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 oskario2 · Mar 02, 2014 at 10:05 AM 0
Share

I'll add the complete code I have for it:

 using UnityEngine;
 using System.Collections;
 
 public class PlayerControler : MonoBehaviour {
 
     public float speed =500;
     public float speedAc = 10;
 
 
     public GUIText countText;
     public GUIText winText;
     private int count;
     //accelerometer
     private Vector3 zeroAc;
     private Vector3 curAc;
     private float sensH = 10;
     private float sensV = 10;
     private float smooth = 0.5f;
     private float GetAxisH = 0;
     private float GetAxisV = 0;
 
     // Use this for initialization
     void Start () {
         count = 0;
         setCountText ();
         winText.text = "";
         ResetAxes();
     }
     
     // Update is called once per frame
     void Update () {
 
     
     }
 
     // Update is called once per frame
     void FixedUpdate () {
 
         if (SystemInfo.deviceType == DeviceType.Desktop) {
             //get input by keyboard
             float movehorizontal = Input.GetAxis ("Horizontal");
             float movevertical = Input.GetAxis ("Vertical");
 
             Vector3 movement = new Vector3 (movehorizontal, 0.0f, movevertical);
             rigidbody.AddForce (movement * speed * Time.deltaTime);
         }
         else 
         {
             //get input by accelerometer
             curAc = Vector3.Lerp(curAc, Input.acceleration-zeroAc, Time.deltaTime/smooth);
             GetAxisV = Mathf.Clamp(curAc.y * sensV, -1, 1);
             GetAxisH = Mathf.Clamp(curAc.x * sensH, -1, 1);
             // now use GetAxisV and GetAxisH instead of Input.GetAxis vertical and horizontal
             // If the horizontal and vertical directions are swapped, swap curAc.y and curAc.x
             // in the above equations. If some axis is going in the wrong direction, invert the
             // signal (use -curAc.x or -curAc.y)
             
             Vector3 movement = new Vector3 (GetAxisH, 0.0f, GetAxisV);
 
             rigidbody.AddForce(movement * speedAc);
 
         }
     }
     
     void OnTriggerEnter(Collider other)
     {
         if (other.gameObject.tag == "Pickup") {
             other.gameObject.SetActive(false);
             count+=1;
             setCountText();
         }
     }
 
     void setCountText()
     {
         countText.text = "Count: " + count.ToString();
         if (count == 13) {
             winText.text = "YOU WIN!";
         }
     }
 
 
     //accelerometer
     void ResetAxes(){
         zeroAc = Input.acceleration;
         curAc = Vector3.zero;
     }
 
 }
avatar image Natasa · Nov 01, 2015 at 09:44 PM 0
Share

I'm working on maze game for Android in Unity 5.1.1f1 and I have troubles with controlling my ball with accelerometer. At start I tried:

 public class PlayerController : MonoBehaviour {
 
     public GameObject sphere;
     public Camera camera;
     public float speed=200;
 
     private Rigidbody myRigidBody;
 
     void Start()
     {
         myRigidBody = gameObject.GetComponent<Rigidbody> ();
     }
     
     void FixedUpdate() 
     {
         float moveH = Input.acceleration.x;
         float moveV = -Input.acceleration.z;
 
         Vector3 move = new Vector3 (moveH, 0.0f, moveV);
         myRigidBody.AddForce (move * speed*Time.deltaTime);
     }    
 }


But the ball is not moving as it should. Then I tried @oskario2 solution. But my ball still doesn't move right. It seems like it's sometimes hard to move left/right/forward/backward, also it's possible my ball will rotate in the opposite direction.

 public class PlayerController : MonoBehaviour {
 
     public float speedAc = 10;
 
     //accelerometer
     private Vector3 zeroAc;
     private Vector3 curAc;
     private float sensH = 10;
     private float sensV = 10;
     private float smooth = 0.5f;
     private float GetAxisH = 0;
     private float GetAxisV = 0;
     
     // Use this for initialization
     void Start () {
 
         ResetAxes();
     }
 
     //accelerometer
     void ResetAxes(){
         zeroAc = Input.acceleration;
         curAc = Vector3.zero;
     }
 
     void FixedUpdate () {
         
         curAc = Vector3.Lerp(curAc, Input.acceleration-zeroAc, Time.deltaTime/smooth);
             
         GetAxisH = Mathf.Clamp(curAc.x * sensH, -1, 1);
         GetAxisV = Mathf.Clamp(-curAc.z * sensV, -1, 1);
             
         Vector3 movement = new Vector3 (GetAxisH, 0.0f, GetAxisV);
         GetComponent<Rigidbody>().AddForce(movement * speedAc);
     }        
 }


Can someone help me, please?

avatar image
1

Answer by olealfheim · Feb 04, 2016 at 10:59 PM

T$$anonymous$$s guy is explaining it for you: https://www.youtube.com/watch?v=HIduNSjAQjU

And have you looked a t$$anonymous$$s video? https://unity3d.com/learn/tutorials/modules/beginner/platform-specific/accelerometer-input

Or t$$anonymous$$s code? http://docs.unity3d.com/ScriptReference/Input-acceleration.html

Comment
Add comment · 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
0

Answer by kprkarthi · Jan 06, 2015 at 01:36 PM

sing UnityEngine; using System.Collections;

public class PlayerControl : MonoBehaviour { public float speed,force;

 void FixedUpdate(){
     if (SystemInfo.deviceType == DeviceType.Desktop) {
                     float moveHorizontal = Input.GetAxis ("Horizontal");
                     float moveVertical = Input.GetAxis ("Vertical");
                     Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
                     rigidbody.AddForce (movement * speed * Time.deltaTime);
             } else {
         float moveHorizontal = Input.acceleration.x;
         float moveVertical = Input.acceleration.y;
         Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
         rigidbody.AddForce (movement * speed * Time.deltaTime);
             }
     }

}

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 RHD · Aug 26, 2016 at 11:41 AM 0
Share

Can't get that one to work. Don't know why, this does but it's pretty crude: using UnityEngine; using System.Collections;

 public class AccelerometerInput : MonoBehaviour {
 
     // Use this for initialization
     void Update () {
 
         transform.Translate(Vector3.forward * Time.deltaTime);
         transform.Translate (Input.acceleration.x, 0, Input.acceleration.z);
 
         }
     
 
 }
  • 1
  • 2
  • ›

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

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

36 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

Related Questions

Get Iphone gforce values. 2 Answers

Unity Realistic accelerometer controls 1 Answer

Input.acceleration on sphere with rigidbody(gravity) 1 Answer

Unity Remote - iPhone Orientation 1 Answer

How to rotate camera using accelerometer in world space? 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