- Home /
How can I get the Time taken for the 2 moving objects to touch each other
Hello, I'm new in Unity as well as a beginner at Programming and Making Games I want to know How Can I calculate the time taken and make a "Count Down" for the 2 objects moving in the same Direction but with different speed to touch each other.
Answer by AaronBacon · Jul 05, 2019 at 01:41 PM
You could simply make a float variable that's at 0 when the game begins, then add Time.deltaTime to it every frame until it collides with the other object. I would use OnTrigerEnter to test for the collisions, assuming both objects have a RigidBody and a Collider, and theres multiple ways you can check if the object the first object has collided with is the other object or not. One way would be to use Unitys Tag system, or just have the Object store the other object as a variable and check with collidername.gameobject.
Answer by metalted · Jul 05, 2019 at 01:59 PM
So this is more of a physics question then a programming question. So because I don't know the situation I'll assume that there is no acceleration involved. We let the 2 objects move on the same line. Object 1 starts at 100m and has a speed of 10 m/s. Object 2 starts at 0m and has a speed of 20m/s. At what time will object 2 overtake / be at the same position as object 1?
The equation used for this is as follows: Xt = V0t + 1/2at^2 + X0. (Xt = Position after t time, V0 = initial speed, a = acceleration, t = time, X0 = initial position). Using this information we can enter the data we have from the objects to create a position function for both:
Object 1: (X0 = 100m, V0 = 10 m/s, a = 0). This will give us the following: Xt = 10t + 100. The middle part will be 0, because a is 0. For object 2 (X0 = 0m, V0 = 20m/s, a = 0) the equation will be: Xt = 20t. (In this case the middle and last part will be 0, so no need to write it down. Now that we entered our data, the math parts comes:
[Object 1: Xt = 10t + 100][Object 2: Xt = 20t]. We know that because they will be on the same position, that both the Xt have to be the same. This means that both equation have to be the same as well. Now we can solve the equation. If Xt = Xt then 10t + 100 = 20t. Now we use the following simple algebra to solve:
10t + 100 = 20t.
100 = 20t - 10t. (Move 10t to the other side, it becomes negative now)
100 = 10t. (Subtract 10t from 20t)
10 = t. (Divide both sides by 10).
t = 10. This means that after t=10 or 10 seconds the positions should be the same. Lets check that:
Object 1: 10t + 100 (with t 10). 10 * 10 + 100 = 200 m.
Object 2: 20t (with t 10). 20 * 10 = 200m.
The answers are the same, so we can conclude that we calculated correctly. The objects will meet at 200m.
Now when acceleration is involved, solving this equation is a whole different thing. You will have to use different kind of math. Just so you know.