- Home /
How can I launch a ball given an angle in degrees and a magnitude?
I'm making a little bullet hell game for fun. Here is what is supposed to happen: I launch a big ball and it goes on for n seconds until it explodes into many smaller balls. These smaller balls are launched into different directions based on the angle intervals I want in the for loop. I was wondering how can I take a degree angle and a magnitude and turn it into a Vector2 so I can change the velocity of each.
So far I have this code:
void Explode()
{
Vector2 spawnLoc = rigidbody2d.position;
Debug.Log("Exploded");
for (int i = 0; i < 360; i += 45) //spawn 8 balls and launch in 45deg intervals
{
Vector2 direction = degToVec2(i);
GameObject smallBall = Instantiate(ball, spawnLoc, Quaternion.identity);
smallBall.GetComponent<Rigidbody2D>().velocity = direction;
}
Destroy(gameObject);
}
and the function:
Vector2 degToVec2(int degree)
{
float x = Mathf.Cos(degree);
float y = Mathf.Sin(degree);
Vector2 vector = (new Vector2(x,y).normalized)*speed;
Debug.Log(vector);
return vector;
}
I almost got it right but its not exactly what I want because the angle of 1 or 2 balls launched goes above 360 degrees. I'm pretty sure its because of the way i'm trying to find x and y.
Answer by BastianUrbach · Nov 12, 2019 at 08:33 AM
Mathf.Sin and Mathf.Cos use radians, not degrees. You should multiply degree with Mathf.Deg2Rad. Also, the .normalized is unnecessary, vector already has a length of 1.
Silly me, for some reason using radians didn't even cross my $$anonymous$$d. Thank you.
Answer by Captain_Pineapple · Nov 12, 2019 at 08:48 AM
Hey there,
in general your mistake is common one: you did not read the documentation ;) Mathf.Cos does not take degree but radians as input. so multiply by 3.141/180.0 and you are good to go.
a way to make your code a bit more smooth:
void Explode(int count)
{
Vector2 spawnLoc = rigidbody2d.position;
Debug.Log("Exploded into " + count + " parts");
float angleInc = 6.282f / count;
for (int i = 0; i < count; i++)
{
Vector2 direction = new Vector2(Mathf.Cos(angleInc * i),Mathf.Sin(angleInc * i))*speed;
GameObject smallBall = Instantiate(ball, spawnLoc, Quaternion.identity);
smallBall.GetComponent<Rigidbody2D>().velocity = direction;
}
Destroy(gameObject);
}
also you need to read into object pooling. Always instantiating and destroying objects will lead to a performance issue sooner or later.
Thank you for the responce. You are also right that my problem was I wasn't using radians. I like your code cleanup too, I will consider it.