Reputation: 57
I'm trying to make shooting with a shotgun, I have already made shooting with one bullet. Code:
Vector2 shootingDirection = new Vector2(joystick.Horizontal, joystick.Vertical);
shootingDirection.Normalize();
if (shootingDirection != new Vector2(0, 0))
{
if(isShotGun) ShotGunShoot(shootingDirection);
GameObject bullet = Instantiate(bulletPrefab, crossHair.transform.position, Quaternion.identity);
bullet.transform.Rotate(0.0f, 0.0f, Mathf.Atan2(shootingDirection.y, shootingDirection.x) * Mathf.Rad2Deg);
bullet.GetComponent<Rigidbody2D>().AddForce(shootingDirection * 10f, ForceMode2D.Impulse);
}
}
But I'm just trying to create two other bullets with a slight deviation from the main one, so that it looks like a fraction, but it does not work correctly. Code:
private void ShotGunShoot(Vector2 dir)
{
GameObject shotGun = Instantiate(bulletPrefab, crossHair.transform.position, Quaternion.identity);
shotGun.transform.Rotate(0.0f, 0.0f, Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 30f);
shotGun.GetComponent<Rigidbody2D>().AddForce((dir + new Vector2(-.3f, 0f)) * 10f, ForceMode2D.Impulse);
shotGun = Instantiate(bulletPrefab, crossHair.transform.position, Quaternion.identity);
shotGun.transform.Rotate(0.0f, 0.0f, Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg + 30f);
shotGun.GetComponent<Rigidbody2D>().AddForce((dir+ new Vector2(.3f, 0f)) * 10f, ForceMode2D.Impulse);
}
As it should be
Here it is now
Thanks for help!
Upvotes: 0
Views: 1927
Reputation: 90649
For the rotation. You can simply set the direction (from your image I can see that your bullet has to fly towards its right vector) like e.g.
shotgun.transform.right = dir;
shotgun.transform.Rotate(0, 0, 30);
For the add force: This uses world space directions.
You always pass in the direction and add the additional offset in world space. So that additional offset goes always in X axis direction regardless in which direction you shoot.
Rather take the direction into account by using the local force Rigidbody.AddRelativeForce
shotGun.GetComponent<Rigidbody2D>().AddForceRelative((shotgun.transform.right + new Vector2(0f, 0.3f)).normalized * 10f, ForceMode2D.Impulse);
This now uses the bullets right direction and additionally uses an offset of 0.3
along its local Y axis.
Btw: If you give your prefab the correct type
public Rigidbody bulletPrefab;
you can skip the GetComponent<Rigidbody>
calls.
Upvotes: 1