]How can I move an object along the axis using touch input?[ SOLVED]

Hey guys, currently I am making a game where you move a barrel to collect coins. I’m at the point of the game where I need to add in mobile input controls. I can move the player left and right using the keyboard but I am not sure how to do the same on mobile devices. I simply want my barrel to move when my player puts their finger on the barrel and moves it left and right to collect coins. I’ve looked up tutorials everywhere but can’t seem to find any that lets you follow the game object using your finger on the x axis.This is my first game, so I’m very new to touch controls.

I generally try to help out people who give me help by providing the script I’ve attempted. However, in this case I only have the keyboard controls script because I don’t know how to use touch for this problem.

using UnityEngine;
using System.Collections;

public class BarrelControlsScript : MonoBehaviour {
    public float barrelspeed = 3f;

    // Use this for initialization
    void Start () {
       
    }

    // Update is called once per frame
    void Update () {
        transform.Translate(Vector3.right * Time.deltaTime * Input.GetAxis("Horizontal") * barrelspeed);
    }
}

I believe you need to use Input.GetTouch for touch input.

OnMouseDown and OnMouseDrag work in touch system. Mesh need collider component to work correctly.

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Collider))]
public class TouchMove : MonoBehaviour {

    float distance = 0f;

    void OnMouseDown()
    {
        #if UNITY_STANDALONE
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        #endif

        #if UNITY_ANDROID
        Touch touch = Input.GetTouch(0);
        Ray ray = Camera.main.ScreenPointToRay(touch.position);
        #endif
        this.distance = Vector3.Distance(ray.origin, this.transform.position);
    }

    void OnMouseDrag()
    {
        #if UNITY_STANDALONE       
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        #endif

        #if UNITY_ANDROID
        Touch touch = Input.GetTouch(0);
        Ray ray = Camera.main.ScreenPointToRay(touch.position);
        #endif

        this.transform.position = ray.origin + ray.direction * distance;
    }
}

I have not been able to verify the code in the android system.In PC working properly.

2 Likes

Yes I know I do but I was just confused on how to do so.

Hey IsGreen. Thank you for the answer. I can’t try this right now but I will try when I get back to unity.

Weird.I’m getting the error ArgumentException : Index out of bounds.

Update : It works on android! But do you know how I can limit input so you can only move along the x-axis?

Update: I fixed this by clamping the z and y axis! Thanks to everyone who replied to the thread!

How you done the clamping of y and z axis?

3 Likes