Distance from start point to end point in percentage in update

笑着哭i 提交于 2020-07-10 17:03:10

问题


float curpos = player.transform.position.magnitude;
float targetpos=GameObject.Find ("target").transform.position.magnitude;
float percentDist = (curCarpos / targetpos) * 100;

What I want to do is calculate percentage along the way from current point which is always moving to end point, starting from zero and once it reaches it should be 100.

For some reason it is starting from 14% decreasing to 0% and then starting from 0%-99%.


回答1:


You do it all wrong. Vectors magnitude in this case it is useless. You need something like this:

Call this before all movement.

float startDistance = Vector3.Distance(player.transform.position, target.transform.position);

And this during movement.

float currentDistance = Vector3.Distance(player.transform.position, target.transform.position);

float percentage =(currentDistance / startDistance) * 100f;



回答2:


I think you should get your starting position in order to get the percentage of the path traveled.

float percentDist = ((curCarpos - startingPos) / (targetpos - startingPos)) * 100;

Just when you start counting the percentage of the way traveled, get the float of your start position and do not update this variable after that at all.



来源:https://stackoverflow.com/questions/34960494/distance-from-start-point-to-end-point-in-percentage-in-update

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