1
votes

I'm trying my first test-game with Unity, and struggling to get my bullets to move.

I have a prefab called "Bullet", with a RigidBody component, with these properties:

Mass: 1
Drag: 0
Angular drag: 0,1
Use grav: 0
Is Kinematic: 0
Interpolate: None
Coll. Detection: Discrete

On the bullet prefab, I have this script:

public float thrust = 10;
private Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();

    rb.AddForce(transform.forward * 100, ForceMode.Impulse);
}

On my playerController script (not the best place for this, I know):

if (Input.GetAxisRaw("Fire1") > 0)
{
    var proj = Instantiate(projectile, transform.position, Quaternion.identity);
}

When I click my mouse, the bullet gets created, but doesn't move. I've added velocity to the rigidbody, which works, but I can't get it to move in the right direction. After googling around, it seems I need to be using rigidBody.AddForce(), which I did, but still can't get my bullet to move.

I've seen the other solution, but this did not work for me either.

Any advice would be appreciated.

Screenshot:

enter image description here

1
Is there a rigidbody on your component?Jlalonde
@Jlalonde, yeah. There is, with the properties set as per the start of my question.WynDiesel
why do you use AddForce and not simply rb.velocity = transform.forward * 100;?derHugo
Ah wait a minute, you're working in 2D, huh? In that case, transform.forward is going to point along the axis that goes forward/backward toward the screen - i.e., it will not visibly affect the position of the object. Try something like transform.right instead.Serlite
actually also .. you would use a RigidBody2D than ... than you would also notice immeditaley that you can not add a Vector3 force but only a vector2 forcederHugo

1 Answers

0
votes

When you're working with 2D in Unity, the main camera basically becomes an orthographic camera (no perspective effects) looking sideways at the game scene along the z-axis. Incidentally, the "forward" direction of a non-rotated object is also parallel to the z-axis.

This means that when you apply a force along transform.forward, you're sending the object down the z-axis - which will not be visible to an orthographic camera looking in the same direction. The quick fix here would be to use a direction that translates to an x/y-axis movement, like transform.up or transform.right.

As derHugo also mentioned in the comments, you might want to look into using Rigidbody2D. There are some optimizations that will allow it to behave better for a 2D game (though you may not notice them until you scale up the number of objects).