- Home /
Toggle between Touch input and accelerometer
Hi everyone,
I'm building a variation of the Space Shooter project for mobile and I want to implement an options menu toggle to change from accelerometer controls to touch based controls for the player ship.
I have already implemented both controls and I was thinking to use PlayerPrefs to make the change constant though out the different playthroughs, but I can't get it to work.
Here is a sample code of what I'm doing inside the Player controller:
void Start ()
{
CalibrateAccelerometer ();
GameObject gameControllerObject = GameObject.FindGameObjectWithTag ("GameController");
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent <Done_GameController>();
}
if (gameController == null)
{
Debug.Log ("Cannot find 'GameController' script");
}
touchControls = gameController.state;
Debug.Log ("Are touch controls on? " + touchControls);
}
Here is what I do inside the Fixed Update of the same Player controller to choose between different inputs:
if (touchControls == 0) {
//Acceleration controls
Vector3 accelerationRaw = Input.acceleration;
Vector3 acceleration = FixAcceleration (accelerationRaw);
movement = new Vector3 (acceleration.x, 0.0f, acceleration.y);
}
if (touchControls == 1) {
//Touch Controls
Vector2 direction = touchPad.GetDirection ();
movement = new Vector3 (direction.x, 0.0f, direction.y);
}
Now on the Gamecontroller script to set toggle options on Accelerometer controls or Touch input controls I call the following methods in the toggle options:
public void SetTouchContols () {
PlayerPrefs.SetInt(TouchControlsKey, 1);
state = PlayerPrefs.GetInt(TouchControlsKey, 1);
Debug.Log ("Touch controls value: " + state);
PlayerPrefs.Save();
}
public void SetAccelerometerControls () {
PlayerPrefs.SetInt(TouchControlsKey, 0);
state = PlayerPrefs.GetInt(TouchControlsKey, 0);
Debug.Log ("Touch controls value: " + state);
PlayerPrefs.Save();
}
Finally here is an image of how I hooked up the toggle group:
I can't manage to get it to work properly and i tried different approaches. I ‘have heard the controls can't be changed on runtime but if the change was made in another scene (e.g. Main menu Scene) could it be done?
Thanks! :)