Help with Mobile Game controls

Lots of mobile games have the type of movement system where the player simply drags the player left and right to avoid object. I’ve looked for a number of tutorials but the code they provide makes the movement really bad and almost impossible to control. Does anyone have experience in this field who can help me?

Here is my code right now:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{

//variables
public float moveSpeed = 300;
public GameObject character;

private Rigidbody2D characterBody;
private float ScreenWidth;

// Use this for initialization
void Start()
{
	ScreenWidth = Screen.width;
	characterBody = character.GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void Update()
{
	int i = 0;
	//loop over every touch found
	while (i < Input.touchCount)
	{
		if (Input.GetTouch(i).position.x > ScreenWidth / 2)
		{
			//move right
			RunCharacter(1.0f);
		}
		if (Input.GetTouch(i).position.x < ScreenWidth / 2)
		{
			//move left
			RunCharacter(-1.0f);
		}
		++i;
	}
}

private void RunCharacter(float horizontalInput)
{
	//move player
	characterBody.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0));

}

}

Here’s my code to detect drag left/right controls in my game which is based on the Docs. Declare startPos as a Vector2 in your variables and minimumMovement as a float and set it to a value that fits your requirements.

if (Input.touchCount > 0) {
    Touch touch = Input.GetTouch(0); // get only the first touch

    switch (touch.phase) {
        case TouchPhase.Began:
            // Record initial touch position.
            startPos = touch.position;
            break;

        case TouchPhase.Ended:
            // Get direction of the movement
            Vector2 direction = touch.position - startPos;
            if (Mathf.Abs(direction.x) > minimumMovement) {
                if (direction.x > 0) {
                    //move right
                } else {
                    //move left
                }
            }
            break;
    }
}

@Anis1808 Thanks for the help. Unfortunately, I’m getting the error “Cannot convert Vector2 to float” on this part.

Vector2 direction = touch.position - startPos;

                if (Mathf.Abs(direction) > minimumMovement)
                {
                    if (direction > 0)
                    {
                        transform.position += transform.right * -speed * Time.deltaTime;
                    }
                    else
                    {
                        transform.position += transform.left * -speed * Time.deltaTime; 
                    }
                }