Home > Back-end >  Can't make bullets land in the right spot
Can't make bullets land in the right spot

Time:11-28

I'm making an FPS game, but the bullets are not hitting in the right spot sometimes the bullets are below the crosshair but the next time it will be way off to the left.

I tried moving the gun tip (aka the thing that spawned the bullets) to aim at the center of the screen but then the bullets just went way of track. The code for launching the bullets is simple. If you can help me make the bullets land where the crosshair is, thank you if not thanks for reading this.

The Code

if(Input.GetMouseButton(0) && Time.time >= nextTimeToFire)
{ 
      Rigidbody rb = Instantiate(Bullet, GunTip.position, Quaternion.identity).GetComponent<Rigidbody>();
      rb.AddForce(GunTip.forward * 500f, ForceMode.Impulse);
}

CodePudding user response:

Difficult to tell what the problem is straight off the bat. Can you share the entire project somewhere? I tried to do this on my own computer and it seems to be working fine for me. One think which comes to my mind is that your GunTip may not necessarily point at the crosshair and so your bullets go off course.

CodePudding user response:

If you draw a triangle (imaginary, right now) between the weapon tip, the crosshair (for simplicity, take it if the weapon tip is right under the crosshair), and the target at which the crosshair points, you'll see a different triangle when the target is 10m away, or 100m.

Based on that, I would do a Raycast "from the" crosshair (in this case, from camera position to camera forward). From that, you'll get where should your bullet arrive, and you can add the force something like that (half pseudo):

[SerializeField] private Transform _camera;
[SerializeField] private Transform _weaponTip;

[SerializeField] private LayerMask _bulletLayerMask;
[SerializeField] private float _range;
[SerializeField] private float _bulletInitSpeed;

private void Update()
{
    if (<can shoot checks>)
    {
        if (Physics.Raycast(_camera.position, _camera.forward, out RaycastHit hit, _range, _bulletLayerMask)
        {
            Rigidbody bullet = <instantiate stuff>;
            // calculating the direction from the weapon tip to the impact point
            bullet.AddForce((hit.point - _weaponTip.position).normalized * _bulletInitSpeed, ForceMode.Impulse);
        }
    }
}
  • Related