transform.forward doesn't work, but transform.up does

I’m sorry if this has been answered before somewhere, but I’ve searched for quite a while and I am unable find a solution.

I’m making a basic shooter mechanic in Unity2D where the player shoots a gun that can be aimed with the mouse.

I’m trying to propel the bullet in the direction of the gun, but when it instantiates it just falls as if transform.forward wasn’t applied at all.

Code:

    public Rigidbody2D bulletPrefab;
    public Transform gunEnd;

if (Input.GetKey (KeyCode.Mouse0)) {
              
        Rigidbody2D bulletInstance;

        bulletInstance = Instantiate(bulletPrefab, gunEnd.position, gunEnd.rotation) as
        Rigidbody2D;

        bulletInstance.AddForce (gunEnd.forward * 5000);
              
}

However, by simply using transform.up instead, it works. (The following code is the same as above except its up, not forward):

    public Rigidbody2D bulletPrefab;
    public Transform gunEnd;

if (Input.GetKey (KeyCode.Mouse0)) {
              
        Rigidbody2D bulletInstance;

        bulletInstance = Instantiate(bulletPrefab, gunEnd.position, gunEnd.rotation) as
        Rigidbody2D;

        bulletInstance.AddForce (gunEnd.up * 5000);
              
}

I ended up rotating the bullet prefab and the transform point where its instantiated by 90 to make the illusion of transform.forward, but I still wanna know why transform.foward isn’t working.

Thanks in advance.

bulletInstance is a ‘Rigidbody2D’, which takes a Vector2 as its force when you AddForce:

Transform’s are 3d though, and Transform.forward is a 3d Vector3. Vector3 when coerced to a Vector2 just redacts the ‘z’ component of the Vector3.

Now, I don’t know what sort of rotation you have on the ‘gunEnd’, but I’m willing to bet its forward is something like <0,0,1>, because the default forward is <0,0,1>.

You might be wanting transform.right. Which default right is <1,0,0>.

At default orientation:
right = x-axis
up = y-axis
forward = z-axis

2 Likes

Ahhh, yeah that would make sense. Tried out transform.right and it did the trick. Sadly enough I found that out moments after creating the thread. Appreciate the break down and for straight up telling me though. Thanks!