void Update() { // accelerate towards target speed if (speed > targetSpeed) { speed -= Time.deltaTime * acceleration; if (speed < targetSpeed) { speed = targetSpeed; } } if (speed < targetSpeed) { speed += Time.deltaTime * acceleration; if (speed > targetSpeed) { speed = targetSpeed; } } float railSpeed = alignedWithRail ? speed : -speed; railDistance += Time.deltaTime * railSpeed; // If they are near the end of the tile and there's no tile to transfer to, change direction if (targetSpeed != 0) { if (railDistance < changeDirectionDistance && !RailIsConnected(currentRail, false)) { targetSpeed = alignedWithRail ? defaultSpeed : -defaultSpeed; } if (railDistance > currentRail.trackLength - changeDirectionDistance && !RailIsConnected(currentRail, true)) { targetSpeed = alignedWithRail ? -defaultSpeed : defaultSpeed; } } // If their position is outside the limits of the tile, try moving to the next one. if (railDistance < 0 && RailIsConnected(currentRail, false) || railDistance > currentRail.trackLength && RailIsConnected(currentRail, true)) { TransferToNextRail(railDistance > 0); } currentRail.PositionVehicleOnRail(transform, railDistance, alignedWithRail); }