- Home /
Question by
Keiji1 · Oct 22, 2021 at 04:43 PM ·
script.scripting beginner
Platform move left and right randomly
Hi, I am pretty new to Unity and I am trying to make a platform jumping game. I got this script working as it should from a Youtube video but I wanted to make the platform move randomly because I have multiple platforms that gonna spawn when I start the game. So basically when the platform spawn 1 should go from left to right and the other should go from right to left.
public Transform pos1, pos2;
public float speed;
public Transform startPos;
Vector2 nextPos;
// Start is called before the first frame update
void Start()
{
nextPos = startPos.position;
}
// Update is called once per frame
void Update()
{
if(transform.position == pos1.position)
{
nextPos = pos2.position;
}
if(transform.position == pos2.position)
{
nextPos = pos1.position;
}
transform.position = Vector2.MoveTowards(transform.position, nextPos, speed * Time.deltaTime);
}
Comment
Best Answer
Answer by Hellium · Oct 22, 2021 at 05:55 PM
public Transform pos1, pos2;
public float speed;
Vector2 nextPos;
// Start is called before the first frame update
void Start()
{
nextPos = Random.value < 0.5f ? pos1 : pos2;
}
// Update is called once per frame
void Update()
{
if(transform.position == pos1.position)
{
nextPos = pos2.position;
}
if(transform.position == pos2.position)
{
nextPos = pos1.position;
}
transform.position = Vector2.MoveTowards(transform.position, nextPos, speed * Time.deltaTime);
}
Your answer
Follow this Question
Related Questions
How do I make a photography function? 0 Answers
Show speed in UI 1 Answer
How to keep the old line text? 1 Answer
how can you make a 3D model slowly become transparent? 2 Answers
loop vs if spell casting script 1 Answer