Hi,
I have a Player and following camera moving in the Z-direction which both start with different speeds, but with the camera behind the Player. I am trying to write a script that will speed up or slow down the Player so that a desired set distance can be reached. At this time, I would like to set the speed of the Player to the same as that of the Camera, so the distance can be maintained.
I have started a basic script which tries to do what I have described, but its not working. If anyone can provide any advice on how to do this that would be great. The script is attached to the MainCamera.
//---
public GameObject PlayerObj;
// The Distance we want to maintain
public float Distance;
// Used to hold the distance between Player and Camera
private float Gap;
private float playerCurrentSpeed;
void Start ()
{
// Store the Player's speed before any changes
playerCurrentSpeed = PlayerObj.GetComponent().Speed;
}
void Update ()
{
Gap = Mathf.Abs(gameObject.transform.position.z - PlayerObj.transform.position.z);
Debug.Log("Gap = " + Gap);
// If the distance is larger than our desired distance..
if (Gap > Distance)
{
// Decrease the speed of the Player to reach the desired distance (every second)
//PlayerObj.GetComponent().Speed -= Time.deltaTime;
PlayerObj.GetComponent().Speed--;
// When the desired distance is reached, set the Player's speed to match the Camera's
}
// If the distance is smaller than our desired distance..
if (Gap < Distance)
{
// Increase the speed of the Player to reach the desired distance (every second)
//PlayerObj.GetComponent().Speed += Time.deltaTime;
PlayerObj.GetComponent().Speed++;
}
else
PlayerObj.GetComponent().Speed = gameObject.GetComponent().Speed;
}
}
↧