Noob_Programer
Noob_Programer

Reputation: 41

Object is not moving

I wanted to make a transfer code for my player game object but it didn't work. I don know why, but I think maybe there is a problem with "Lerp" part. What is the problem?

public class Player_Ctrl : MonoBehaviour 
{
    public float movespeed = 3.0f;

    private void Update () 
    {
        Vector3 PlayerPos = transform.position;
        Vector3 NextPos   = transform.position;

        if (Input.touchCount != 1) return;

        float ChangingPos = this.transform.position.x * movespeed;
        NextPos.x = ChangingPos;
        Touch touch = Input.GetTouch(0);

        if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Stationary)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
            RaycastHit hit;

            if (!Physics.Raycast(ray, out hit)) return;

            if (hit.collider.tag == "LEFTSIDE" || hit.collider.tag == "RIGHTSIDE")
                transform.position = Vector3.Lerp(PlayerPos, NextPos, Time.deltaTime);
        }
    }
}

Upvotes: 0

Views: 133

Answers (1)

Tovi7
Tovi7

Reputation: 2953

Lerp is a function that interpolates between two positions, using the third argument, which is a value between 0 and 1.

You use Time.deltaTime as your third argument. So if your Position and NextPosition are always the same, (And Time.deltaTime will be roughly the same if you have a constant frame rate), then the output of the Lerp will always be the same.

Furthermore, this piece of code:

float ChangingPos = this.transform.position.x * movespeed;

probably doesn't do what you want it to do. This will take a fraction of your current position, and set that as the next position.

You probably want to move your character with move speed, but in a smooth manner. If so, I would recommend setting a RigidBody on your Player GameObject, and use forces on the RigidBody instead. This will work better, especially if you want to do anything pseudo physically at some point.

So try something like (after you attach the rigid body as a component):

//In start:
_rigidBody = GetComponent<RigidBody>();

//In update:
if(_YOUR_CONDITION_){
  _rigidBody.AddForce(Vector3.right * movespeed / Time.deltaTime);
}

Upvotes: 3

Related Questions