How to make a 3D object to follow my finger from left to right on Android?

615 Views Asked by At

I'm new to unity and game developing so I've tried to make a game. Everything worked well until I thought about changing from making the game from PC to Android.

The movement on PC worked well but I can't seem to find any code for kind of the same movement for Android.

This is what I use for the PC movement

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;

    public float forwardForce = 2000f;
    public float sidewayForce = 500f;

    // Update is called once per frame
    void FixedUpdate()
    {
        rb.AddForce(0, 0, forwardForce * Time.deltaTime);

        if ( Input.GetKey("d") )
        {
            rb.AddForce(sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }

        if (Input.GetKey("a"))
        {
            rb.AddForce(-sidewayForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }

        if (rb.position.y < -1f)
        {
            FindObjectOfType<GameManager>().EndGame();
        }
    }
}

and this is what I used for the android movement but the only problem is that it doesn't go forward and a player doesn't even move. This script somehow moves the platform that the player is on.

public class PlayerMovANDROID : MonoBehaviour
{

    // Use this for initialization
    GameObject hitObj;
    RaycastHit hit;
    private float speed = 1;

    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        foreach (Touch touch in Input.touches)
        {
            switch (touch.phase)
            {
                case TouchPhase.Began:
                    Ray ray = Camera.main.ScreenPointToRay(touch.position);
                    if (Physics.Raycast(ray, out hit, 10))
                    {
                        hitObj = hit.collider.gameObject;
                    }
                    break;
                case TouchPhase.Moved:

                    // If the finger is on the screen, move the object smoothly to the touch position          
                    float step = speed * Time.deltaTime; // calculate distance to move
                    if (hitObj != null)
                        hitObj.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, hitObj.transform.position.z));
                    break;
            }
        }
    }
}
1

There are 1 best solutions below

1
On

Are you using GUI buttons to move the player?

If not you can use: horizontal= Input.GetAxis("Mouse X") and vertical =Input.GetAxis("Mouse Y") to detect where the player has placed their finger on the screen.

Once you get those you should assign them to the object through Transform through

transform.Rotate(horizontal, vertical ,z);

transform.Translate(horizontal, vertical ,z);

transform.position(horizontal, vertical ,z);

Check this for more info.