Unity Developers Question: Download Unity 3D Developer PDF

Consider the following code snippet below:

class Mover : MonoBehaviour
{
Vector3 target;
float speed;

void Update()
{

}
}
Finish this code so the GameObject containing this script moves with constant speed towards target, and stop moving once it reaches 1.0, or less, units of distance?

Tweet Share WhatsApp

Answer:

class Mover : MonoBehaviour
{

Vector3 target;
float speed;

void Update()
{
float distance = Vector3.Distance(target,transform.position);

// will only move while the distance is bigger than 1.0 units
if(distance > 1.0f)
{
Vector3 dir = target - transform.position;
dir.Normalize(); // normalization is obligatory
transform.position += dir * speed * Time.deltaTime; // using deltaTime and speed is obligatory
}
}
}

Download Unity 3D Developer PDF Read All 27 Unity 3D Developer Questions
Previous QuestionNext Question
Can threads be used to modify a Texture on runtime?
Can threads be used to move a GameObject on the scene?
Consider the snippet below:
class RandomGenerator : MonoBehaviour
{
public float[] randomList;

void Start()
{
randomList = new float[1000000];
}

void Generate()
{
System.Random rnd = new System.Random();
for(int i=0;i<randomList.Length;i++) randomList[i] = (float)rnd.NextDouble();
}
}
Improve this code using threads, so the 1000000 random number generation runs without spoiling performance.
Okay, we're going to work through a problem here?