Moving an object with vector3.MoveTowards

泪湿孤枕 提交于 2019-12-02 05:21:41

问题


I am working on a game app with Unity. I have an issue when it comes to move a GameObject .

In my game, when the player swipes up with his device, the GameObject moves from a point A to B, and when he swipes down, it goes from B to A.

I wrote a C# script with the game logic, but I have an issue when it comes to this.

The problem is that the GameObject moves instantly from A to B.

Here is the code line I use to move my GameObject :

transform.localPosition = Vector3.MoveTowards (PositionA,PositionB,Time.deltaTime * speed);

speed is a float with a value of 10.0f.

I would like my GameObject to move slowly to point A to B. And despite the changes on speed value, nothing change, it's still moving instantly.

How can I fix that? (I tried with Vector3.Lerp and I had the same results).


回答1:


Vector3.MoveTowards takes the current position, the target position, and the step, but it seems like your first argument here is origin of the move, rather than current position. Normally you'd do this something like this, in your Update():

transform.localPosition = Vector3.MoveTowards (transform.localPosition, PositionB, Time.deltaTime * speed);

with the current position as the first argument.




回答2:


Here is how to use MoveTowards:

void Update()
{
    float step = speed * Time.deltaTime;
    transform.position = Vector3.MoveTowards(transform.position, PositionB, step);
}

LearnMore



来源:https://stackoverflow.com/questions/40489102/moving-an-object-with-vector3-movetowards

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!