Debugging Challenge
- Keshav Batra
- May 13, 2021
- 1 min read
After almost a week of struggling, I finally debugged this script so that the cube would move.
{
public Transform targetTransform; // the transform contains the target position
Vector3 startingPosition; // has the starting location at the beginning
float speed = 5f; // The cube speed has a float value of 5
float startTime, journeyLength;
// Start is called before the first frame update
void Start()
{
startingPosition = transform.position; // it is storing the cubes initial position at the starting position variable
startTime = Time.time; // Start time has the same value as Time.time
journeyLength = Vector3.Distance(startingPosition, targetTransform.position); // it stores the cubes distance from its initial position to the target position
}
// Update is called once per frame
void Update()
{
float distCovered = (Time.time - startTime) * speed; // Distance that the player covered has the same value as time.time subtracting from startTime times speed
float fractionOfJourney = distCovered / journeyLength; // Distance that the player has covered is divided by the journeyLength (Part of the journey in a value of 0 to 1)
transform.position = Vector3.Lerp(startingPosition, targetTransform.position, fractionOfJourney); // The initial position equals the value as the Vector3.Lerp and it stores the cube from the initial position to the target position and finally a fraction of the destination (this line is the movement of the cube) (value of 0 to 1)
}
}
The main thing that I had to do was make a reference to the object and make the target Transform public. That allowed me to drag in the target location and make the cube move by itself. Here's the end result:
Comments