How do I convert a Vector3 to Vector2 in a elegant way?

I made an alternative way to check for multible defenders in a square. It works fine but it looks a bit heavy in the if-sentence. My first thought was to minus _defender.transform.position with GetSquareClicked() but _defender.transform.position is a Vector3 and GetSquareClicked() is a return of a Vector2. Is there a elegant way to make convertions of Vectors?

private bool AlreadyOneInTheField()
{
bool oneMoreInTheField = false ;

    foreach(Defender _defender in FindObjectsOfType<Defender>())
    {
        if (_defender.transform.position.x - GetSquareClicked().x == 0 && _defender.transform.position.y - GetSquareClicked().y == 0)
        {
            oneMoreInTheField = true;
        }
    }
    return oneMoreInTheField;
}

It should convert it automatically, if it doesn’t then just use vector3 instead, to be honest I don’t see the need to use vector 2, if you think of it, it adds no real value or advantage.

GetSquareClicked() return a Vector2 and I’m afraid that if I change it, it’s going to cause problems later in the course if this function is used.

Maybe this, but it´s still looks very heavy and not elegant :frowning:

if (_defender.transform.position - new Vector3(GetSquareClicked().x, GetSquareClicked().y,0) == new Vector3(0,0,0))

You just have to convert the position to a vector2, which Unity does pretty much on its own, here’s the manual.

Vector2 vTEMP = _defender.transform.position;
if (vTEMP - GetSquareClicked().x == Vector2.zero)
{
    //Do something
}

Okay …So simpel. thanks for your answer …

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms