Adding or removing objects depending on height of parent object in 2D game
For example, I have 20x40 chain sprite scaled by 5 so it is 100 x 200 (it is a prefab now). I have object which spawns these prefabs. I want to spawn enough prefabs from this object to the upper side of camera. For example, I have this object on coordinates 0x200. It must spawn one prefab (because prefab's height is 200). If this objects moves to Y 400, its spawns one more prefab on top of previous. How can I do that?
Answer by Genei_180 · Oct 27, 2016 at 02:48 PM
Check the Objekts Position you want to follow and save the Output in the Funktion Playerposition(Prefab Player). This is for a 2D Game but it can be easily extended to 3D when the concept is understood.
The Code gets the Position of the Player and based on that returns an integer. This is Multiplied by the Map size. So for example:
If Renderdistance is 3. Your Player is at (0/48) this returns Mathf.RoundtoInt(48/200) = 0
So you have to Place your Objekt at Position.x = 0 * MapLength = 0.
But if it is at (0/214) this returns Mathf.RoundtoInt(214/200) = 1
So you have to Place your Objekt at Position.x = 1 * MapLength = 200.
for (int x = renderdistance / 2 * -1; x < renderdistance / 2; x++) {
for (int y = renderdistance / 2 * -1; y < renderdistance / 2; y++) {
Vector2 ppos = Playerposition (Player);
ppos.x += x * MapLength;
ppos.y += y * MapHight;
public Vector2 Playerposition(Transform Player)
{
int x = Mathf.RoundToInt (Player.transform.position.x / MapLength) * MapLength;
int y = Mathf.RoundToInt (Player.transform.position.y / MapHight) * MapHight;
return new Vector2 (x, y);
}
I hope i could help you. If you didn't understood it completely feel free to ask me about it.