Quick question about migration to C#

Hey guys,

I’m refactoring my entire project to C#, and I’ve got a small problem I’m hoping you can help me out with quickly. Here is what I WANT to do :slight_smile: It works with Vector3.Lerp, but I need it to be Vector2. The startPoint and endPoint are Vector3 values, but I think they should get converted automatically, right? There must be an easy way to do it! I just need to keep the transform.position.z constant.

transform.position = (Vector2.Lerp(startPoint, endPoint,
                              (Time.time - startTime) /
                              (DurationBetweenPoints * Vector2.Distance(startPoint, endPoint) * 2)));

You could use:

Vector2 pos = (Vector2.lerp (new Vector2 (startPoint.z, startPoint.y), new Vector2 (endPoint.x, endPoint.y), (Time.time - startTime) / (DurationBetweenPoints * Vector2.Distance (new Vector2 (startPoint.z, startPoint.y), new Vector2 (endPoint.x, endPoint.y) * 2)));

transform.position = new Vector3 (pos.x, pos.y, 0);

Or you can make some helper functions:

Vector2 Vector3To2 (Vector3 vector) {

    return new Vector2 (vector.x, vector.y);

}

Vector3 Vector2To3 (Vector2 vector) {

    return new Vector3 (vector.x, vector.y, 0);

}

Vector2 pos = (Vector2.Lerp (Vector3To2 (startPoint), Vector3To2 (endPoint), (Time.time - startTime) / (DurationBetweenPoints * Vector2.Distance(Vector3To2(startPoint), Vector3To2(endPoint)) * 2)));

transform.position = Vector2To3 (pos);

Thank you Dman, that helps a lot!

There’s no point in that because it’s always been available in Unity. Because they’re operators, there’s no need to call functions manually at all. Vector2s and 3s are completely interchangeable (as long as z isn’t necessary).

http://unity3d.com/support/documentation/ScriptReference/Vector2-operator_Vector3.html
http://unity3d.com/support/documentation/ScriptReference/Vector2-operator_Vector2.html

Thanks Jesse, I suspected that might be the case! As it turns out, I only needed to typecast my comparison of transform.position and endpoint to vector2, and it worked perfectly :slight_smile:

Silly me! I had a feeling they were there but a quick scan of the scripting reference turned up 0 results. Must be going blind =P