x


Is there an int based class/struct like Vector2?

I am currently doing a lot of 2D texture based work, for which I am currently using Vector2 to store x,y coordinates. However, due to Vector2's x and y being floats, I have to typecast a lot in my source. There is no use for the floating point because all of these all pixel based coordinates, and therefore whole numbers. I just use Vector2 because it is handy to store an x and y :)

Is there a class for this, or do I have to write my own struct for this?

Thanks!

more ▼

asked Mar 08, 2011 at 08:07 PM

Jordii gravatar image

Jordii
173 29 24 29

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

There is no such class or struct built into Unity.

Easy to implement though (C#) ...

public struct IntVector2
{
    int x;
    int y;

    int sqrMagnitude
    {
        get { return x * x + y * y; }
    }
}

You would probably want to follow the example of Vector2 and implement as many of its methods as make sense for your application. I've shown sqrMagnitude as an example.

more ▼

answered Mar 08, 2011 at 08:16 PM

yoyo gravatar image

yoyo
8.1k 59 67 124

OK too bad. I did my research but couldn't find any. When I started at AS3 I made the mistake of writing a few struct-like classes (like Point! :D) which later on were already in AS3. With a lot more functionality! So I didn't want to make that mistake again ;)

Thanks yoyo!

Mar 08, 2011 at 08:34 PM Jordii
(comments are locked)
10|3000 characters needed characters left

I might recommend just writing an extension method, so that you don't have to rewrite everything, like yoyo said.

public static class Vector2Extensions {
    public static IntVector2 ToIntVector2 (this Vector2 vector2) {
        int[] intVector2 = new int[2];
        for (int i = 0; i < 2; ++i) intVector2[i] = Mathf.RoundToInt(vector2[i]);
        return new IntVector2 (intVector2);
    }
}

public struct IntVector2  {
    public int x, y;

    public IntVector2 (int[] xy) {
        x = xy[0];
        y = xy[1];
    }   
}
more ▼

answered Mar 08, 2011 at 09:02 PM

Jessy gravatar image

Jessy
18.1k 207 173 283

Just be careful not to constantly convert back and forth or you'll chew up cycles and possibly have precision problems. (I'd probably give serious thought to using Vector2 out of the box.)

Mar 09, 2011 at 07:48 AM yoyo
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x321
x199
x183
x114

asked: Mar 08, 2011 at 08:07 PM

Seen: 6682 times

Last Updated: Mar 08, 2011 at 08:07 PM