Need Help // My 2D "Asteorids" ship shoots bullets that don't go in the expected direction

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;
        }
    }

Welcome! This should be pretty straightforward… I’m guessing your ship might not be oriented “up” or something. If this is the case, you may have to redo your ship prefab.

But first, understand what orientation you WANT your ship in, and make sure that is correct (eg, do you want 0 degrees to be UP, or 0 to be RIGHT, etc.)

Use Debug.Log() to print the vectors you do for each shot, as well as the facing vector for the ship.

ALSO: for this:

The bullets may be colliding with the ship. You should prevent this with layers / layermasks / physics collision table.

Beyond that, here’s how to really get down into what is actually happening:

You must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Many thanks @Kurt-Dekker ! Great Advice!

Thanks to using Debug.Log() I was able to confirm that there was no problem with the direction of the bullet. Then I confirmed that the bullet was actually collisioning with the ship.

So I was able to solve it quickly using the Layer Collision Matrix. :slight_smile:

1 Like

Excellent! Glad to hear you’re back online!

ALSO: writing an asteroids style ship game is ALWAYS fun, and you can add just about any feature to it you want and learn continuously as you do.

You sound like you already have the Correct Attitude™ and I hope you have all the best success in Unity, which is the best game engine in the world after all.

Check out this guy’s attitude: it might appeal to you too:

https://www.youtube.com/watch?v=b3DOnigmLBY

1 Like