- Home /
This question was
closed Dec 15, 2018 at 03:27 PM by
hexagonius for the following reason:
no description of the problem provided
Question by
krnimpuse · Dec 15, 2018 at 02:53 PM ·
c#2dscripting problem
I am trying to spawn multiple asteroids but only one of them is screen wrapping.
Asteroid Body
public class Asteroidbody : MonoBehaviour { CircleCollider2D cc; float radius; float magnitude;
void Start ()
{
cc = GetComponent<CircleCollider2D>();
radius = cc.radius;
}
public void Initilise(Direction dir)
{
float angle = Random.Range(15, 45);
if(dir == Direction.Left)
{
angle = angle + 180;
}
else
{
if(dir==Direction.Up)
{
angle = angle + 90;
}
else if(dir==Direction.Down)
{
angle = angle - 90;
if(angle<0)
{
angle = 360 + angle;
}
}
}
Vector2 direction = new Vector2(Mathf.Cos(angle * Mathf.Deg2Rad), Mathf.Sin(angle * Mathf.Deg2Rad));
magnitude = Random.Range(2, 4);
GetComponent<Rigidbody2D>().AddForce(direction * magnitude, ForceMode2D.Impulse);
}
void OnBecameInvisible()
{
Vector2 position = transform.position;
// check left, right, top, and bottom sides
if (position.x + radius < ScreenUtils.ScreenLeft ||
position.x - radius > ScreenUtils.ScreenRight)
{
position.x *= -1;
}
if (position.y - radius > ScreenUtils.ScreenTop ||
position.y + radius < ScreenUtils.ScreenBottom)
{
position.y *= -1;
}
// move ship
transform.position = position;
}
}
Asteroid Spawner
public class AsteroidSpawner : MonoBehaviour { [SerializeField] GameObject asteroidPrefab;
Asteroidbody astbody1;
Asteroidbody astbody2;
Asteroidbody astbody3;
Asteroidbody astbody4;
void Start ()
{
GameObject aster1=Instantiate<GameObject>(asteroidPrefab, new Vector3((ScreenUtils.ScreenLeft)/16, ScreenUtils.ScreenTop,-Camera.main.transform.position.z), Quaternion.identity);
astbody1 = aster1.GetComponent<Asteroidbody>();
GameObject aster2 = Instantiate<GameObject>(asteroidPrefab, new Vector3((ScreenUtils.ScreenLeft) / 16, ScreenUtils.ScreenBottom, -Camera.main.transform.position.z), Quaternion.identity);
astbody2 = aster2.GetComponent<Asteroidbody>();
GameObject aster3 = Instantiate<GameObject>(asteroidPrefab, new Vector3(ScreenUtils.ScreenLeft, ScreenUtils.ScreenBottom/8, -Camera.main.transform.position.z), Quaternion.identity);
astbody3 = aster3.GetComponent<Asteroidbody>();
GameObject aster4 = Instantiate<GameObject>(asteroidPrefab, new Vector3(ScreenUtils.ScreenRight, ScreenUtils.ScreenBottom/8, -Camera.main.transform.position.z), Quaternion.identity);
astbody4 = aster4.GetComponent<Asteroidbody>();
astbody1.Initilise(Direction.Down);
astbody2.Initilise(Direction.Up);
astbody3.Initilise(Direction.Right);
astbody4.Initilise(Direction.Left);
}
}
Comment