0
votes

Helllo, peeps! I'm making a mobile video game and i'm having troubles with my touch movement system. Here's how i want it to work:

https://www.youtube.com/watch?v=X5tC7y1_ARA

1) Only move on the X axes (not a problem here)

2) When i press on the screen, the object shouldn't teleport on the position of the finger.

3) The Oject should move from the initial position of the object to the current position of the object in Real Time, no teleports. I calculate the current position of the object like this:

object's current position = object's current position + current position of the finger - initial position of the finger

Here's what i got so far

        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            if (touch.phase == TouchPhase.Began)
            {
                Vector3 startPos = touch.position;  //Initial Position
            }
            if (touch.phase == TouchPhase.Moved)
            {
                Vector3 movementDistance = new Vector3(touch.position.x - startPos.x, 0, 0);
                Vector3 direction = Camera.main.ScreenToWorldPoint(movementDistance);
                Vector3 currentPos = Camera.main.ScreenToWorldPoint(transform.position);
                transform.position = new Vector3(Mathf.Clamp(currentPos.x + direction.x, -121, 121), transform.position.y, transform.position.z);
            }
        }

For some reason this doesn't work properly. The object teleports to random positions and it doesn't move the object as i hoped.

Can you help me detected my problem? If not, do you know any other methods?

1

1 Answers

1
votes

read about "Variable scope" - https://msdn.microsoft.com/en-us/library/ms973875.aspx

try this:

Vector3 startPos;
float movementSpeed = 0.1f; // adjust this to your liking

void Update()
{
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
        if (touch.phase == TouchPhase.Began)
        {
            startPos = touch.position;  //Initial Position
        }
        if (touch.phase == TouchPhase.Moved)
        {
            Vector3 movementDistance = new Vector3(touch.position.x - startPos.x, 0, 0);
            Vector3 direction = Camera.main.ScreenToWorldPoint(movementDistance);
            transform.position = new Vector3(Mathf.Clamp(transform.position.x + movementSpeed * direction.x, -121, 121), transform.position.y, transform.position.z);
        }
    }
}