Search Unity

Move an object at a certain speed when given distance and time

Discussion in 'Scripting' started by nostalgicbear, Dec 14, 2016.

  1. nostalgicbear

    nostalgicbear

    Joined:
    Mar 21, 2013
    Posts:
    99
    Hi, so I am trying to do the following. I am trying to move an object from A to B at a certain speed, over a certain time. The speed and time are determined by the length of an audioclip. So for example, if the audioclip is 10 seconds long, I want the object to take 10 seconds to travel from A-B at whatever the correct speed is.

    The distance is always going to be a set distance (25 units).

    I assumed that seeing as I have the distance (25), and I have the time (10), that calculating the speed was going to be simple using the "SPEED = DISTANCE / TIME" formula, however that isnt working. Perhaps I'm messing up somewhere in my update where the object actually moves. localPosition is used as it is a child object I am moving and I want to move relevant to the parent.

    This is driving me nuts because I know it should be so simple. Can someone please tell me where I am messing up?

    Thanks!

    Code (CSharp):
    1. float distance = 25;
    2. float time = 10;
    3.  
    4.  
    5. void FixedUpdate()
    6. {
    7.   if (move)
    8.         {
    9.              needle.localPosition = Vector3.MoveTowards(needle.localPosition, needleEndPos,((distance / time) * Time.deltaTime);
    10.          
    11.         }
    12. }
    13.  
     
  2. dragonice501

    dragonice501

    Joined:
    Dec 2, 2015
    Posts:
    146
    This should be somewhat useful.

     
  3. nostalgicbear

    nostalgicbear

    Joined:
    Mar 21, 2013
    Posts:
    99
    Solved the issue. It was down to the fact that I forgot to use "transform.localPosition" when calculating distance. Thanks for the link though. Pretty useful videos anyway.