- Home /
2d spawn across screen
Hi! I'll just start by saying that I am a complete nooby moron when it comes to programming (art i can do, code not so much) but i'm working on a small 2d mobile game for a uni project.
At this point i'm trying to figure out how to spawn, say, 3 random sprites off screen, and have them go across the screen, from right to left, i have no code to show because everything I've tried so far hasn't worked and is undoubtedly wrong, i'd rather start from scratch.
These three objects will be fish, two being worth points, one poison that kills the player if they catch it (via their shark avatar on the left side of the screen)
Answer by Vallar · Apr 03, 2016 at 07:45 AM
Hello,
I am a bit new myself however, you can do the below as an example (since there isn't too much details I am guessing half of what is needed).
To create the object off screen, check the coordinates on the point you want to spawn at (for this example let's say x = -4.62, y = 2 and since it is 2D so z = 0.
To spawn in C# you use the Instantiate keyword and provide a prefab name. To move there are a few methods we'll use MoveTowards as it is easy.
Our code would look similar to the below: public GameObject fishPrefab; public float fishSpeed;
private Vector3 spawnPosition = new Vector3 (-4.62f, 2, 0);
private Vector3 position1 = new Vector3 (2, 2, 0);
void Start()
{
// To Spawn:
GameObject fish = Instantiate(fishPrefab, spawnPosition, Quaternion.identity) as GameObject;
// To move:
fish. transform.position = Vector3.MoveTowards(fish.transform.position, position1, Speed * Time.deltaTime);
}
To make it random you can add the below:
public GameObject[] fish;
private int randomPicker;
private Vector3 spawnPosition = new Vector3 (-4.62, 2, 0);
private Vector3 position1 = new Vector3 (2, 2, 0);
void Start()
{
for (int i = 0; i < 3; i++)
{
randomPicker = Random.Range(1, 4);
switch (randomPicker)
{
case 1:
GameObject fish1 = Instantiate(fish[1], spawnPosition, Quaternion.identity) as GameObject;
fish1. transform.position = Vector3.MoveTowards(fish1.transform.position, position1, Speed * Time.deltaTime);
break;
case 2:
GameObject fish2 = Instantiate(fish[2], spawnPosition, Quaternion.identity) as GameObject;
fish2. transform.position = Vector3.MoveTowards(fish2.transform.position, position1, Speed * Time.deltaTime);
break;
case 3:
GameObject fish3 = Instantiate(fish[3], spawnPosition, Quaternion.identity) as GameObject;
fish3. transform.position = Vector3.MoveTowards(fish3.transform.position, position1, Speed * Time.deltaTime);
break;
}
}
}
Hope that helps.
Your answer
Follow this Question
Related Questions
Hide gameobject? 1 Answer
How to make background loop and camera follow spawned gameobjects? 1 Answer
How do you create a constantly spawning set of random missiles that move vertically down? 1 Answer
How to Spawn an Object in between Randomly Spawned Objects with no Overlapping? 0 Answers
Multiple Cars not working 1 Answer