Simple script, somewhat complicated issue involving changing a dimension of a vector at certain times.
In my game, I have objects called "cloud" moving from the bottom of the screen to the top. After the get above the top of the screen, they appear at the bottom and move upward again.
So, when my "cloud" object appears at the bottom of the screen, I want it to begin moving both upward at a determined rate but also to drift towards one of the sides of the screen at a random rate. The problem I have is with giving the cloud a new random vector each time it re-appears at the bottom to add to its position.
Here's is my code:
using UnityEngine; using System.Collections;
public class Clouds : MonoBehaviour {
public float StartingPosition;
public Vector3 UpCloud;
public Vector3 SideCloud;
public Sprite sprite1;
public Sprite sprite2;
public float offset1;
public float offset2;
private SpriteRenderer spriteRenderer;
void Start () {
spriteRenderer = GetComponent<SpriteRenderer>();
float RandomFl = Random.Range(offset1, offset2);
transform.position = new Vector3 (RandomFl, StartingPosition, -0.7f);
spriteRenderer.sprite = sprite1;
AddtoCloud ();
}
// Update is called once per frame
void Update () {
if (transform.position.y >= StartingPosition * -1) {
float RandomFl = Random.Range (offset1, offset2);
transform.position = new Vector3 (RandomFl, StartingPosition, -0.7f);
ChangeSprite ();
AddtoCloud();
} else {
transform.position += (UpCloud + SideCloud);
}
}
void ChangeSprite () {
if (spriteRenderer.sprite == sprite1) {
spriteRenderer.sprite = sprite2;
} else {
spriteRenderer.sprite = sprite1;
}
}
void AddtoCloud () {
Vector3 SideCloud = new Vector3 (Random.Range (-0.05f, 0.05f), 0f, 0f);
}
}
The problem with this code is that when I use "AddtoCloud," I'm not actually changing the vector "SideCloud," I'm making a new one. If I were to actually change SideCloud in AddtoCloud, I think my code would work. Does anybody know how I could do that, or how to get a new vector each time within the "if" statement?
Answer by Statement · Dec 20, 2015 at 01:59 AM
The problem with this code is that when I use "AddtoCloud," I'm not actually changing the vector "SideCloud," I'm making a new one. If I were to actually change SideCloud in AddtoCloud, I think my code would work. Does anybody know how I could do that, or how to get a new vector each time within the "if" statement?
void AddtoCloud () {
Vector3 SideCloud = new Vector3 (Random.Range (-0.05f, 0.05f), 0f, 0f);
}
Change it to...
void AddtoCloud () {
SideCloud = new Vector3 (Random.Range (-0.05f, 0.05f), 0f, 0f);
}
I could of sworn I tried that! But it worked, so thank you!