- Home /
Random Y Axis Direction On Prefab Within Boundaries (C#)
Hi guys, I've been having this issue for ages and none of my Google searches have turned up anything decent that helps me.
So basically I have a script that generates instances of 5 prefabs every second, in that those prefabs have a script that tells them to move left on the x axis (2D game), now what I need is for that script to give each instance of each prefab a random direction on the y axis to travel (up or down obviously), but it has to be different each time.
I also need to constrain it somehow, so it doesn't go out of a certain range, and when it hits the edge of that range, I need it to change direction to the opposite direction on the y axis.
Here is what I've most recently tried:
using UnityEngine;
using System.Collections;
public class PowerItem : MonoBehaviour {
public float itemUp = 0.1f;
public float itemLeft = 0.7f;
public float x;
float y;
float z;
Vector3 pos;
void Update () {
//transform.position = Vector2(Random.Range (1,4),Random.Range (1,4),10);
transform.position -= Vector3.right * itemLeft * Time.deltaTime;
x = 0;
y = Random.Range(-100, 100);
z = 0;
pos = new Vector3(-x, y, z);
transform.position = pos * itemUp * Time.deltaTime;
}
}
Is there anybody who would be kind enough to help me out here? I'm really stuck.
Your answer
![](https://koobas.hobune.stream/wayback/20220613201038im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
moving random objects to random positions 1 Answer
Emerging Gap when moving my "Snake" 1 Answer
Random Movement : 2d 1 Answer
Input.GetButton not working 1 Answer
How do I move my object slowly from its original position? 2 Answers