Home > Blockchain >  Converting Vector2 to Vector2Int
Converting Vector2 to Vector2Int

Time:05-21

I'm trying to convert Vector2 to Vector2Int, since that's what I'm using as a cursor in my game. I want it to snap onto pixels instead of freely move around like it's doing now, I have no idea how to convert the current Vector2, so perhaps someone could hint at what to do, or just tell me. I keep getting errors when I try it.

public RectTransform rect;

private Canvas myCanvas;

void Awake()
{
    this.myCanvas = base.GetComponent<Canvas>();
}

// Update is called once per frame
void Update()
{
    Vector2Int pos;
    RectTransformUtility.ScreenPointToLocalPointInRectangle(myCanvas.transform as RectTransform, Input.mousePosition, myCanvas.worldCamera, out pos);
    rect.position = myCanvas.transform.TransformPoint(pos);
}

If someone could help me that would be nice! I've been stuck on this for a good while now.

CodePudding user response:

It's very simple, you can do it using a Vector2, don't need a Vector2Int, look my example:

RectTransformUtility.ScreenPointToLocalPointInRectangle(myCanvas.transform as RectTransform, Input.mousePosition, myCanvas.worldCamera, out Vector2 pos);
pos.x = (int)pos.x;
pos.y = (int)pos.y;
rect.position = myCanvas.transform.TransformPoint(pos);

You may also want to have a look at some rounding methods as: https://docs.unity3d.com/ScriptReference/Mathf.RoundToInt.html

If you have any doubts, feel free to ask...

  • Related