- Home /
Smooth tail followscript
Hi! We are making a train game and I want the first wagon to follow the train and the second wagon to follow the first etc..
The script is added as a component to the train (player) and have an array of segments where the first segment is the train it self. The position of the segments are based on the rotation of the previous segment so it saves all rotations in a list and makes the segments follow those rotations with a delay.
Unfortunately this method results in a very unsmooth behavior. Is there a good way to lerp angles or something like that?
This is how the script looks like:
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class Follow : MonoBehaviour { public Transform[] segments;
private List<Quaternion> rotationHistory;
private Vector3 pos = new Vector3();
private float angleY, angleX;
void Start ()
{
//Init a startvalue for the rotationHistory
rotationHistory = new List<Quaternion>();
rotationHistory.Add(transform.rotation);
//Startvalue for the wagons based on the train
angleY = (transform.rotation.eulerAngles.y + 45 )* (Mathf.PI / 180);
angleX = (transform.rotation.eulerAngles.x + 45 )* (Mathf.PI / 180);
}
void Update()
{
//Add the current rotation in the list
rotationHistory.Add(transform.rotation);
}
void LateUpdate ()
{
//For through the segments (i = 0 r train, i > 0 = wagons)
for(int i = 1; i < segments.Length; i++)
{
try
{
//Put the angles to previous angles
angleY = (rotationHistory[rotationHistory.Count - (2 * i)].eulerAngles.y + 45 )* (Mathf.PI / 180);
angleX = (rotationHistory[rotationHistory.Count - (2 * i)].eulerAngles.x + 45 )* (Mathf.PI / 180);
}
catch
{
//If no previous angles exists use the current ones
angleY = (rotationHistory[rotationHistory.Count - 1].eulerAngles.y + 45 )* (Mathf.PI / 180);
angleX = (rotationHistory[rotationHistory.Count - 1].eulerAngles.x + 45 )* (Mathf.PI / 180);
}
//Calculate a position based on the rotation
pos.x = Mathf.Cos(angleY) - Mathf.Sin(angleY);
pos.y = (Mathf.Sin(angleX) - Mathf.Cos(angleX));
pos.z = -(Mathf.Sin(angleY) + Mathf.Cos(angleY));
pos *= i * 1.1f;
//Apply the position
segments[i].position = pos;
//Rotate the segment towards the previous segment
segments[i].rotation = Quaternion.LookRotation(segments[i - 1].position - segments[i].position);
}
}
}
Cant you use the build in script called Smoothfollow?
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Camera follow help? 1 Answer
Ideas for getting SmoothFollow camera to follow right behind? 0 Answers
C# Online help 1 Answer
Enemy Follow Script Help 2 Answers