Im new so I don’t know what I am doing. I’m trying to get a object from the left side to move to a random position on the right side every 5 seconds. For example, an object on coordinates (-4, 0) to coordinates (4, RandomY). Any extra solutions and tips are appreciated as well. Thanks!
`
{
float timer;
float timeToMove;
public float speed;
float yPos;
public Vector3 desiredPos;
void Start()
{
timer = 0;
timeToMove = 3;
yPos = Random.Range(-4.5f, 4.5f);
desiredPos = new Vector3(transform.position.x, yPos, transform.position.z);
}
void Update()
{
timer += Time.deltaTime;
if (timer >= timeToMove)
{
// I copied this, I do not know what this does
transform.position = Vector3.Lerp(desiredPos, transform.position, Time.deltaTime * speed);
if (Vector3.Distance(transform.position, desiredPos) <= 0.01f)
{
yPos = Random.Range(-4.5f, 4.5f);
desiredPos = new Vector3(transform.position.x, yPos, transform.position.z);
timer = 0.0f;
}
}
}
}
`
Could you not just use these two lines of code here? 'yPos = Random.Range(-4.5f, 4.5f);
desiredPos = new Vector3(transform.position.x, yPos, transform.position.z); ’
These are used to set the object to a position on the left I assume. If you want to set the object to a random position on the right, I think you could just change ‘desiredPos’ with a new variable and then create a new variable for x, y, or z depending on which axis you’re moving the object on.
for anyone wanting to do something similar, this is my finished code.
`
public float timer;
float timeToMove;
public float speed;
public float yPos;
float xPos;
Vector3 desiredPos;
void Start()
{
timer = 0.0f;
timeToMove = 3;
xPos = -4;
desiredPos = transform.position;
}
void Update()
{
timer += Time.deltaTime;
if (timer > timeToMove)
{
transform.Translate(new Vector3(1, yPos, 0) * speed * Time.deltaTime);
}
if (timer > 3)
{
if (timer < 3.1f)
{
yPos = Random.Range(-1.0f, 1.0f);
}
}
if (transform.position.x > 4)
{
transform.position = new Vector3(xPos, 0, 0);
timer = 0.0f;
}
else
{
timer += Time.deltaTime;
}
}
}
`
for anyone wanting to do something similar, this is my finished code.
`
public float timer;
float timeToMove;
public float speed;
public float yPos;
float xPos;
Vector3 desiredPos;
void Start()
{
timer = 0.0f;
timeToMove = 3;
xPos = -4;
desiredPos = transform.position;
}
void Update()
{
timer += Time.deltaTime;
if (timer > timeToMove)
{
transform.Translate(new Vector3(1, yPos, 0) * speed * Time.deltaTime);
}
if (timer > 3)
{
if (timer < 3.1f)
{
yPos = Random.Range(-1.0f, 1.0f);
}
}
if (transform.position.x > 4)
{
transform.position = new Vector3(xPos, 0, 0);
timer = 0.0f;
}
else
{
timer += Time.deltaTime;
}
}
}
`