- Home /
Help Adding Local Force and Rotating in a For Loop
I'm making an action platformer and the game play centers around the player shooting a shotgun like this
So I already have the gun shooting singular bullets and dealing damage to enemies what I need help with is two things. The first one is simple here's my code, I need help adding velocity along a local axis. the next thing is a little bit more difficult, I need to rotate each bullet between the negative and positive value of bulletSpreadAngle. so I can then add the local force along the x axis.
float numOfBullets = 5f;
float bulletSpeed = 10f;
float bulletSpreadAngle = 45f; // How far the farthest bullet will be tilted
GameObject bulletPrefab; // Defined in the editor, this is the prefab that all bullets are spawned from
void ShootWeapon()
{
// bullet's rotation = spread distance / number of bullets
// Every iteration in the loop add onto the rotation and rotate the bullet that much
for (int i = 0; i < numOfBullets; i++)
{
for (float j = -bulletSpreadAngle; j < bulletSpreadAngle; j += bulletSpreadAngle / numOfBullets)
{
GameObject bullet = Instantiate(bulletPrefab, gunEnd.position, Quaternion.identity);
Rigidbody2D projectileRigidbody = bullet.GetComponent<Rigidbody2D>();
if (transform.localScale.x > 0)
{
//bullet.transform.rotation = new Quaternion(Quaternion.identity.x, Quaternion.identity.y, Quaternion.identity.z * j, Quaternion.identity.w);
projectileRigidbody.velocity = new Vector3( bulletSpeed, projectileRigidbody.velocity.y);
}
else if (transform.localScale.x < 0)
{
projectileRigidbody.velocity = new Vector2(-bulletSpeed, projectileRigidbody.velocity.y);
}
}
}
}
Answer by Diukrone · Jan 16, 2018 at 02:16 AM
You can try using Vector3(new Vector3(0,0,0) and Mathf.SmoothDamp and Mathf.Lerp. Check it on Unity API!
That's not exactly what I'm looking for. Those change something in for instance the Update loop. What I'm looking for is some way to add on say 9 degrees every iteration of a for loop.
Answer by Dray · Jan 16, 2018 at 03:33 PM
Sine and cosine will do the job:
projectileRigidbody.velocity = new Vector2(
Mathf.Sin(j),
Mathf.Cos(j)
) * bulletSpeed;