Make an object path across another object

I’m trying to make a cube (cart placeholder) follow along a track:

track

I’m wondering what the best method is to achieve this. A pathing system like Spline Controller will not suffice because I don’t want to have to configure the waypoints on the track; it should just follow it. I was thinking of creating the script like so;

  1. Set the target track object
  2. Position the host object in the middle of the track object
  3. Keep raycasting diagonally downwards from the top-front of the cube to see if there’s still a track in front of it
  4. Move forward if so
  5. Optionally have the cart/cube reverse direction if the track ends, in case it doesn’t loop
  6. Optionally create the path once at script startup rather than dynamically in case the track is static

Would this work, and would it be o.k. performance wise (in other words; is there a better alternative, performance wise)? Also, what do I need to look in to to make the cart/cube turn across curves so it doesn’t end up looking silly?

The way I see it, to make this work you need two surfaces, one for left and right, and one for up and down. A groove in the track will work, or a simple angle will work…even the edge of the track. Instead of raycasting diagonally downward, I’d place an empty sensor objects in the groove/angle. It would raycast down and to the right. The sensor would adjust itself so that it maintained a set offset to the groove/angle. If you had the object position lag the sensor position, you can use the different positions to define an angle to use as the forward for movement and for the rotation of the cube. You can add a forward raycast to the sensor to sense a stop at the end of the groove/angle. Consider using Collider.Raycast() instead of Physics.Raycast().

why not use itweenpath system. just modified some line according to what you want and you are good to go.