- Home /
[2d] When I shoot bullets they have different speeds
Hello, I have a 2d platforming shooter where the player can shoot where the mouse aims. Everything works, the aiming and shooting are all functional, but for some reason even if I shoot in the same spot some bullets will have different speeds than others. I have had this problem working on another project but I kind of just shrugged it off because I was not putting much effort into it, but I want this project to feel right.
Here is some sample code:
void Update()
{
//Changing Rotation of Gun
direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - this.transform.position;
angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90f;
this.transform.eulerAngles= new Vector3(0, 0, angle);
//Shooting the Gun
if(Input.GetMouseButtonDown(0) || Input.GetKeyDown("z"))
{
Shoot();
}
}
void Shoot()
{
GameObject spawnedBullet = Instantiate(bullet, spawnPoint.transform.position, GetComponent<Transform>().rotation);
spawnedBullet.GetComponent<Rigidbody2D>().AddForce(direction.normalized * Time.deltaTime * bulletSpeed,ForceMode2D.Impulse);
print(spawnedBullet.GetComponent<Rigidbody2D>().velocity);
}
Thanks in advance!
Answer by MiB775 · Jun 22, 2020 at 08:16 PM
I think you shouldn't multiply by Time.deltaTime.
That worked quite well, thanks! But I do have a follow up, doesn't this make the bullet's movement based off frame rate, from which I heard is not good?
Time.deltaTime is the ellapsed time since the last frame, so by including it the bullet is dependent on the frame rate. Also it varies each frame and so thats why the speed is inconsistant. You would use Time.deltaTime if moving using Transform.Translate for example, since it is called every frame.