I am making a top-down 2D game, and I have a character which automatically rotates towards the nearest enemy unit and fires. I would like to convert the unit’s rotation into X and Y vectors, which are passed to the bullet object to determine which direction the bullet moves.
The problem is, the bullets either fire only to the right. If I remove the radian transformation, they fire in different directions, but not in a way related to the objects orientation, and only in about 1/3rd of possible directions (which makes me think this is something to do with converting between orientaiton and XY).
The unit’s fire bullet code is:
// Update is called once per frame
void Update()
{
if (Time.time > next_fire)
{
next_fire = Time.time + fire_rate;
fire();
}
}
void fire()
{
bullet_pos = transform.position;
GameObject new_bullet = Instantiate(projectile, bullet_pos, Quaternion.identity);
Quaternion direction = transform.rotation;
var radians = direction.z * Mathf.Deg2Rad;
x = Mathf.Cos(radians);
y = Mathf.Sin(radians);
new_bullet.GetComponent<bullet_flying>().velX = x;
new_bullet.GetComponent<bullet_flying>().velY = y;
}
The bullet’s code is:
public float velocity = 10;
public float velX = 0f;
public float velY = 0f;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
Destroy(gameObject, 5);
rb = GetComponent<Rigidbody2D > ();
}
// Update is called once per frame
void Update()
{
rb.velocity = new Vector2(velX*velocity, velY*velocity);
}