Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

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:
    98
    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:
    98
    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.