I have a fixed orthographic camera for my 2D game with a scrolling background and I want to spawn my sprites randomly outside the camera bounds and have them move inside and out of the camera and get destroyed. Currently I’m using the script below but its generating a lot of sprites within the camera bounds and not working as intended. I cant point out where i’m going wrong?
[33778-screenshot+2014-10-17+01.03.22.jpg|33778]
Random Sprite Generation Code:
public Vector2 speed = new Vector2(10,10);
//Moving direction
public Vector2 direction = new Vector2(-1,0);
private Vector2 movement;
public int numToSpawn;
private Vector3 position;
float CameraHeight;
float CameraWidth;
int spawned = 0;
public bool spawn;
void Start ()
{
CameraHeight = Camera.main.camera.orthographicSize;
CameraWidth = CameraHeight * Screen.width/Screen.height;
}
void Update ()
{
movement = new Vector2(speed.x * direction.x, speed.y * direction.y);
if(spawn)
{
position = new Vector3(Random.Range(-0.5f,0), Random.Range(0f,CameraHeight),0f);
Instantiate(gameObject,position,transform.rotation);
spawned++;
}
}
void FixedUpdate()
{
rigidbody2D.velocity = movement;
}
//Checking Collision property
void OnTriggerEnter2D(Collider2D col)
{
EffectsScript effects = gameObject.GetComponent<EffectsScript>();
if(effects.IsColorise)
{
effects.RandomColorise();
}
if(effects.IsMelody)
{
effects.Melody();
}
}
I take it this script is attached to the camera? What is the position of the camera? Is the idea for the sprites to appear just on the left side of the camera boundaries? Also, is there a particular reason why the x-coordinate of the sprites is randomized instead of just being placed at a fixed distance outside the camera view?
– ozone