Hi all,
I’m working on a custom train system, works great except in one proeblem and it makes me want to give up and start something else…
Here’s the problem:
Wagon or more of them that follow the loco don’t strictly follow it. Visualy it looks like distance between them is not constant but moves a bit. This can best be seen in the attached video. Whole thing is controlled by scripts, except for left and right borders in track which are colliders to keep everything in track.
Script sets wagon to be “coupled” which makes wagon run the same speed and acceleration script as loco in FixedUptade() using movePosition at the end. I even tried to force the transorm to keep distance and measure distance with Vector3.Distance as you see in picture and distance is the same but visually looks like it is not.
Piece of code for moving loco, contains some ballast but anyway…:
Vector3 position = this.transform.position;
if (this.railBelowTrain)
position[1] = railBelowTrain.transform.position.y + 0.02f;
if (forward)
{
if (speed < 0 || moving && speed < maxSpeed)
speed = speed + speedRate * Time.fixedDeltaTime;
else if (moving && speed >= maxSpeed)
speed = maxSpeed;
else if (speed > 0)
{
speed = speed - speedRate * Time.fixedDeltaTime;
if (speed < 0)
speed = 0;
}
else
speed = 0;
}
else
{
if (speed > 0 || moving && speed > -maxSpeed)
speed = speed - speedRate * Time.fixedDeltaTime;
else if (moving && speed <= -maxSpeed)
speed = -maxSpeed;
else if (speed < 0)
{
speed = speed + speedRate * Time.fixedDeltaTime;
if (speed > 0)
speed = 0;
}
else
speed = 0;
}
Vector3 movement = transform.right * speed * Time.fixedDeltaTime;
rb.MovePosition(position + movement);
if (this.attachedWagoonsRear.Count > 0)
{
float distance = 0.9f;
transform.position = (transform.position - this.attachedWagoonsRear[0].transform.position).normalized * distance + this.attachedWagoonsRear[0].transform.position;
Debug.Log(Vector3.Distance(this.transform.position, this.attachedWagoonsRear[0].transform.position));
}
for(int i = 0; i < this.attachedWagoonsRear.Count; i++)
{
this.attachedWagoonsRear[i].GetComponent<WagonController>().forward = this.forward;
this.attachedWagoonsRear[i].GetComponent<WagonController>().moving = this.moving;
this.attachedWagoonsRear[i].GetComponent<WagonController>().speedRate = this.speedRate;
this.attachedWagoonsRear[i].GetComponent<WagonController>().maxSpeed = this.maxSpeed;
}
for (int i = 0; i < this.attachedWagoonsFront.Count; i++)
{
this.attachedWagoonsFront[i].GetComponent<WagonController>().speed = this.speed;
}