- Home /
Question by
Tomas_14 · Sep 14, 2017 at 08:48 PM ·
2dpositionrandompositioning
Get a 2D Random Position for Object
I was trying to make a game object choose a random position for itself in a 2d environment but everytime I call it (with a button for example), first it goes always to the (0,0) coordinates and then when I call it a second time it chooses a random location but outside the space where I want it? Could you help me plz?
public GameObject Label1;
public GameObject Button;
float x;
float y;
Vector2 pos1;
void Start()
{
Button btn = Button.GetComponent<Button>();
btn.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
Label1.GetComponent<RectTransform>().position = pos1;
//Label Random Position1
x = Random.Range (-130, 130);
y = Random.Range (-135, 50);
pos1 = new Vector2 (x, y);
}
Comment
Answer by houseyokeswaran · Sep 14, 2017 at 08:54 PM
You need to call Label1.GetComponent().position = pos1; after you actually set pos1.
Answer by Raimi · Sep 14, 2017 at 09:16 PM
public Vector2 RandomPosition( Vector2 minbounds, Vector2 maxBounds )
{
Vector2 newPos = new Vector2();
newPos.x = Random.Range(minBounds.x, maxBounds.x);
newPos.y = Random.Range(minBounds.y, maxBounds.y);
return newPos;
}
Then...
void OnClick()
{
TargetObject.transform.position = RandomPosition(minBounds, maxBounds);
}