Vector3.MoveTowards()无法正常工作,无法解决?

时间:2019-03-20 16:38:18

标签: c# unity3d

我真的是编码新手,英语不是我的主要语言,所以请原谅任何愚蠢的错误和我的英语。

我正在研究一种将玩家移动到点击点的移动系统,脚本上的所有内容似乎都可以正常工作,但是在游戏选项卡中,玩家根本没有移动。我已经阅读了许多有关Vector3.MoveTowards()的信息,但没有任何帮助。

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 个答案:

答案 0 :(得分:0)

好吧,您正在更改currentpos的值,但不要将其分配回transform.position,例如这里

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