0
votes

I'm really new to coding and English isn't my main language, so forgive any dumb errors and my English.

I'm working on a movement system that moves the player to click point, everything on the script seems to work, but in the game tab the player doesn't move at all. I already read a lot of information about Vector3.MoveTowards(), but nothing worked for me.

Vector3 currentpos;
Vector3 targetpos;

bool ismoving = false;

public float speed = 10f;


void Update()
{
    currentpos = transform.position;
    move();

    if (Input.GetMouseButtonDown(0))
    {
        click();
    }

}


void click()                         //get the position of the click using a raycast//
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if(Physics.Raycast(ray, out hit))
    {
        targetpos = hit.point;
        targetpos.y = 0f;            //only whants to move the player in the x and z axis//


        ismoving = true;
        move();
    }
}


void move()
{
    if (ismoving==true)
    {
        if (Vector3.Distance(currentpos,targetpos)>0.1f)  //if distance between current position and target position is greater than 0.1f player should move//
        {
            currentpos = Vector3.MoveTowards(currentpos, targetpos, speed * Time.deltaTime);

            Debug.Log("Current Position is:" + currentpos + " and target position is" + targetpos);
        }

        if(Vector3.Distance(currentpos,targetpos)<0.1f)
        {
            ismoving = false;
        }
    }
}

In the console the current position and the target position are right but the player doesn't move.

1
Please avoid using links to images of text. Instead, copy and paste the text into your answer directly.Ctrl S

1 Answers

0
votes

Well, you are chaning the value of currentpos but never asign it back to transform.position e.g. here

currentpos = Vector3.MoveTowards(currentpos, targetpos, speed * Time.deltaTime);
transform.position = currentpos;