I have such a code. It moves the object along the Z axis, but it moves only in one direction no matter where the finger moves to the right to the left, but it is necessary that, depending on which way the finger moves! How to do it?

using UnityEngine; public class Follower : MonoBehaviour { #region ================================= PRIVATE FIELDS private readonly float _speed = 0.1f; private Vector2 _startPos; #endregion #region ============================== PRIVATE METHODS private void Update() { if (Input.touchCount > 0) { var touch = Input.GetTouch(0); switch (touch.phase) { case TouchPhase.Began: _startPos = touch.position; break; case TouchPhase.Moved: var dir = touch.position - _startPos; var pos = transform.position + new Vector3(transform.position.x, transform.position.y, dir.y); transform.position = Vector3.Lerp(transform.position, pos, Time.deltaTime * _speed); break; } } } #endregion } 
  • and why here var pos = transform.position + new Vector3(transform.position.x, transform.position.y, dir.y); Do you take the y-coordinate of dir.y , and not the x-coordinate? - Alexander Danilovsky
  • So that it moves when the smartphone is in an upright position - Aimon Z.

1 answer 1

The problem is in the coordinates that you get from the wheelbarrow. touch.position - returns the position in screen coordinates, and this is from (0,0) in the lower left corner, to (width, height) in the upper right. Accordingly, you always plus a positive number and the character will never go left or down.

Screen coordinates must be brought to the world via the ScreenToWorldPoint camera method . If you have a camera with a MainCamera tag, the cast may look like this:

 var direction = Camera.main.ScreenToWorldPoint(touch.position); 

The direction variable will contain the coordinates of the wheelbarrow in global space and by working with them you will already get more expected behavior)

  • Thank you, this is what you need - Aimon Z.