- Home /
Random X position 2D
I was trying to make an object move to a random X position. But when I run the code the object just stays in the same position.
public class RandomSpawn : MonoBehaviour
{
Rigidbody2D body;
float Y = 3.71f;
public bool findNewPos = false;
float Xmax = 3.71f;
float Xmin = -6.0f;
float X = 0f;
Vector2 Pos;
// Start is called before the first frame update
void Start()
{
body = GetComponent<Rigidbody2D>();
findNewPos = true;
}
void Update()
{
if(Y == -3.47f)
{
findNewPos = true;
}
if(findNewPos == true)
{
X = Random.Range (Xmin, Xmax);
Pos = new Vector2 (X, Y);
}
}
Answer by Mrintoxx · May 31, 2020 at 02:47 PM
You are calculating the new position but never tell to the gameobject to move.You can use transform.Translate. You can also simplify your code :
Rigidbody2D body;
float Y = 3.71f;
public bool findNewPos = false;
float Xmax = 3.71f;
float Xmin = -6.0f;
Vector2 Pos;
void Start()
{
body = GetComponent<Rigidbody2D>();
findNewPos = true;
}
void Update()
{
if(Y == -3.47f) // I don't understand fo what are you doing this ?
{
findNewPos = true;
}
if(findNewPos == true)
{
Pos = new Vector2 (Random.Range(Xmin, Xmax), Y);
transform.Translate(Pos);
// body.AddForce(Pos); You can also use the rigidbody you've previously declared
}
}
Tell me more about what are you tryin to do, so i can help you better
pos should also probably be a vector3 for transform.translate
Yeah my bad, i've wrotten that from $$anonymous$$d :) Doc here
I forgot to delete the if statement. That was for when the object reaches a certain level I wanted it to find a new position and go X position and go back up top.
Your answer
![](https://koobas.hobune.stream/wayback/20220612235731im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
C# Transform modification. 1 Answer
Making a race car positioning system 5 Answers
How to rotate an object to face the direction it's going? 1 Answer