W,A,S,D Keys mapping to Motion Detection (Accelerometer) Script - How to change controls (Mobile2PC)

Hi

I am using the moveHorizontal & moveVertical C# commands as shown below and want to change this line of code to simple accelerometer equivalent (of course there is no W,A,S,D keys on a mobile is there?) without breaking the code, game or assets and including other parts of the code (such as collision detection).

In theory then I can have 2 scripts (one for iOS and Android) and one for PC and with the minimum 1 or 2 lines of code change can make the game work on both platforms. If the accelerometer is used to tilt the ball left or right that is fine as A or D and if the phone is tiled up and down that is perfect for W and S.

Can someone point to the simplest solution?

Many thanks.

using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
    public float speed;
    public Text countText;
    public Text winText;
    private Rigidbody rb;
    private int count;
    void Start ()
    {
        rb = GetComponent<Rigidbody>();
        count = 0;
        SetCountText();
        winText.text = "";
    }
    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
        rb.AddForce(movement * speed);
    }
    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 >= 12)
        {
            winText.text = "You Win!";
        }
}
}
  • updated code tag with Kurts comment.

Couple of things. First up, please view the first post on the forum in order to format your code so it is readable.

Second up, check out the various ways you can trigger different behavior on different platforms. There are many, some at compile time, some at runtime, for instance:

Compile time:

#if UNITY_ANDROID
  // put android-compiled-only code here
#endif

Run time:

if (Application.isMobilePlatform)
{
  // put mobile-only code here
}

or

 if (Application.platform == RuntimePlatform.IPhonePlayer)
{
  // put iphone-only code here, but it WILL be compiled on non-iphone targets too (see #ifdef above)
}