I’m trying to make a defence game on 2D unity but I’m having trouble with the bullet not moving forward
================================================================================
public class gunShoot : MonoBehaviour
{
public float shootSpeed;
private float timeTillNextShot;
public GameObject bullet;
public GameObject gunBarrel;
void Update()
{
if(Input.GetMouseButtonDown(0) == true && timeTillNextShot <= 0)
{
Instantiate(bullet, gunBarrel.transform.position, Quaternion.identity);
timeTillNextShot = shootSpeed;
Rigidbody2D tempRigid = bullet.GetComponent();
tempRigid.AddForce(transform.forward, ForceMode2D.Impulse);
}
timeTillNextShot -= Time.deltaTime;
}
}
================================================================================
The mass of the bullet is 0.001, has no gravity, no drag and no constraints.
You are trying to apply a force to the prefab instead of the new bullet instance.
var clone = Instantiate(bullet, gunBarrel.transform.position, Quaternion.identity);
timeTillNextShot = shootSpeed;
Rigidbody2D tempRigid = clone.GetComponent<Rigidbody2D>();
2 Likes
Everything Praetor says is spot on, but also:
Keep your masses and velocities within a few orders of magnitude of one another, as with your speeds. The entire Unity physics system is based on 32-bit floating point numbers, which can only represent between 6 and 9 decimal places of accuracy. Intermediate calculations (impacts, offsets, etc.) can consume a few of those decimal places, so making masses or velocities tiny or huge will almost certainly cause you all kinds of weird glitchy errors, sorta like the GTA IV swingset of death (see Youtube for video).
1 Like
Adding more to what I said above, if you want a really fast bullet, obviously just use a laserbeam (Raycast) and it will always instantly hit anything at any range.
If you want a fast bullet that actually takes time to pass across a large world, and yet still reliably hits stuff, it’s often better to just raycast ahead of the bullet and move it yourself, without the physics system, without any collider on the bullet. This approach lets you do things like bullet drop each frame, and see if you hit anything, know precisely where the bullet “splash” is (from the RaycastHit info), etc.
That’s how I shoot these bullets in my Jetpack Kurt Space Flight game combat mode:
You can see the bullets dropping off in the distance.
1 Like