Replace Input. Get Axis (Horizontal) with touch input

Am practicing for quiet a while in unity. Am new to programming.

mTransform.Translate(Vector3.right*speed*Input.GetAxis("Horizontal")*Time.deltaTime);

I need to change this to a touch movement. I need to move a simple cube with touch either by drag or swipe in horizontal and vertical. Thanks in advance.

1 Like

Use this one,

// Moves object according to finger movement on the screen
var speed : float = 0.1;
function Update () {
	if (Input.touchCount > 0 && 
	  Input.GetTouch(0).phase == TouchPhase.Moved) {
	
		// Get movement of the finger since last frame
		var touchDeltaPosition:Vector2 = Input.GetTouch(0).deltaPosition;
		
		// Move object across XY plane
		transform.Translate (-touchDeltaPosition.x * speed, 
					-touchDeltaPosition.y * speed, 0);
	}

OR can use this one also!

    float pointer_x = Input.GetAxis("Mouse X");
    float pointer_y = Input.GetAxis("Mouse Y");

    if (Input.touchCount > 0)
    {
        pointer_x = Input.touches[0].deltaPosition.x;
        pointer_y = Input.touches[0].deltaPosition.y;
    }

So, things you need to know:

  1. You’ll probably want to run your code on PC/Mac/Editor as well as on a touch device, so, you’ll want to learn how to check what machine you are running on, and use the appropriate scripting APIs.
  2. Touches are nothing like key presses. Touches can start and disappear when the user lifts their finger. Touches can be joined by other touches when the user uses more fingers. If the touch moves it can be hard to know in what direction the finger is moving, until the finger has moved a certain distance.
  3. Touch screen sizes are all different (see Screen Size here). So, you’ll not want to use pixels when you measure how fingers have moved, and instead, may want to use a percentage of the screen size.
  4. See the examples on the Input.GetTouch() API page for a quick crash course.

Can this be used for Unity 2018 LTS?

1 - If yes, do I apply the code directly? I don’t really understand the contents above.
2 - I don’t see any tutorials in the learn unity website. Are there any tutorials - perhaps outside Unity websites that teach every details so I can understand better?