I am very new to GD, and I’m trying to develop a simplified version of Asteroids.
The problem I’m now encountering is that while I would expect bullets to be shoot in the direction of the ship, they don’t. And they seem to be adding some kind of Force to the ship when facing certain direction.
There is something really confusing to me. I’m using “thrustDirection” as the variable that holds the Vector2 on which the ship is facing, and I’m using it both to addForce to the ship to move in the direction it is facing as well as firing bullets in the same direction. Nevertheless, it only seems to be working for the thrust but not for the bullets… The bullet will never go in a certain 180 degrees direction (Diagonal left = Half quadrant 1 + quadrant 2 + half quadrant 3), but in the other 180 degree space, they work as I’d expect.
Here a link to a couple short clips. One just rotating and hitting the input button to thrust and the other one just rotating and hitting the input button to fire the bullets.
https://drive.google.com/drive/folders/1gWeZq3VmsMKoYcvO884zkxfelS2ONiT2?usp=sharing
My Update and FixedUpdate Script for the Ship:
void FixedUpdate()
{
if (Input.GetAxis("Thrust") != 0)
{
rb.AddForce(thrustDirection*thrustForce,ForceMode2D.Force);
}
rb.velocity = Vector2.ClampMagnitude(rb.velocity, maxSpeed);
if(goFire)
{
GameObject bullet = Instantiate<GameObject>(prefabBullet);
bullet.transform.position = transform.position;
Rigidbody2D rbBullet = bullet.GetComponent<Rigidbody2D>();
rbBullet.AddForce(thrustDirection * maxBulletForce,ForceMode2D.Force);
goFire = false;
}
}
private void Update()
{
if(Input.GetAxis("Rotate")!=0)
{
float roatationAmount = rotateDegreesPerSecond * Time.deltaTime * Input.GetAxis("Rotate");
transform.Rotate(Vector3.forward, roatationAmount);
Vector3 rotation = transform.eulerAngles;
float angleRotatedInDegrees = rotation.z+90;
float angleRotatedInRadians = Mathf.Deg2Rad*angleRotatedInDegrees;
thrustDirection = new Vector2(Mathf.Cos(angleRotatedInRadians), Mathf.Sin(angleRotatedInRadians));
}
if (Input.GetAxis("Fire") != 0)
{
if (fireBullet == true)
{
goFire = true;
fireBullet = false;
}
}
else
{
fireBullet = true;
}
}