- Home /
Question by
RatchetMiles · May 30, 2015 at 05:21 PM ·
androidaccelerometergyroscoperoll a ballport
[Roll a Ball] How do I control the ball with the gyroscope/accelerometer?
I'm trying to take what I learned from the Roll a Ball tutorial and make a functional version for Android. The code I had in mind doesn't work in Unity 5.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class movement : MonoBehaviour {
public float speed;
public Text CountText;
public Text winText;
public Vector3 userAcceleration;
private Rigidbody rb;
private int count;
void Start ()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText ();
winText.text = "";
Screen.sleepTimeout = SleepTimeout.NeverSleep;
}
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);
rb.AddForce (movement * speed);
}
else
{
float moveH = Input.gyro.userAcceleration.x;
float moveV = Input.gyro.userAcceleration.y;
Vector3 movement = new Vector3 (moveH, 0.0f, moveV);
rb.AddForce(movement * speed * Time.deltaTime);
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ("pick up"))
{
other.gameObject.SetActive (false);
count = count + 1;
SetCountText();
}
}
void SetCountText()
{
CountText.text = "Count: " + count.ToString ();
if (count >= 16)
{
winText.text = "Win";
}
}
}
Comment
Answer by 1hella · Jun 05, 2015 at 05:05 PM
moveHorizontal = Input.acceleration.x;
moveVertical = Input.acceleration.y;
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed * 2);
That worked for me.
Hi., is this to be added in the Desktop part or the Phone Part? Or ins$$anonymous$$d of them both, do I just have to add this single code snippet to manage both the Desktop as well as the Phone part? I'm a beginner.
Thanks in Advance :)
Answer by Aren-Rahman · Jun 01, 2015 at 05:53 PM
I am also struggling to do the same thing, we both have the same problem. Make sure to watch this document: http://unity3d.com/learn/tutorials/modules/beginner/platform-specific/accelerometer-input