Jdosaj0606
Jdosaj0606

Reputation: 73

How to get player to move from one x position to another?

When I swipe left or right I am trying to move my player game object to the left or right using the x position.

void OnSwipeLeft()
{
    var oldPosition = transform.position;
    var newPosition = transform.position;
    newPosition = newPosition.x - 1;

    Debug.Log("Swipe Left");
    if((controlLocked == "n"))
    {
        transform.position = Vector3.MoveTowards(oldPosition, newPosition, Time.deltaTime * switchLaneSpeed);
        //horizVel = -2.5f;
        //StartCoroutine(stopSlide());
        controlLocked =  "y";
     }
    }

When I swipe left I need my player to move to the X position -1 and when I swipe right I need it to move to X position 1. The code above is what I tried, but I am getting errors where I am declaring new and old position.

Upvotes: 0

Views: 58

Answers (1)

Aaron Cheney
Aaron Cheney

Reputation: 134

The problem here is that you are trying to assign a float value to a Vector3. The error message should read Cannot implicitly convert type float to UnityEngine.Vector3.

What you want is something like this:

void OnSwipeLeft()
{
    Vector3 oldPosition = transform.position;
    Vector3 newPosition = transform.position;
    newPosition.x -= 1;

    Debug.Log("Swipe Left");
    if (controlLocked == "n")
    {
        transform.position = Vector3.MoveTowards(oldPosition, newPosition, Time.deltaTime * switchLaneSpeed);
        controlLocked = "y";
    }
}

Upvotes: 1

Related Questions