Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Bullet fire: follows camera and overshoot after 1sec

Discussion in 'Physics' started by Erenquin, Nov 12, 2020.

  1. Erenquin

    Erenquin

    Joined:
    Apr 9, 2018
    Posts:
    164
    Hello,
    as the titles I have an extremely strange behavior with bullet fire system.

    What happens is that the bullet is correctly instantiated and moves when fired.
    But for some short time, if I move the camera it follows it.
    Then it kind of overshoot in the target direction.

    I implemented something very simple, actually a simplified version of this tutorial:

    Well most implementation are the same.
    I get the center point of the screen with fpsCamera.ViewportPointToRay(0.5f, 0.5f, 0)
    Calculate the direction: hit point - spawnpoint
    Then instantiate the bullet and addforce to it.

    Below is my code.
    If you have any idea what could cause this issue I would be grateful :)

    Code (CSharp):
    1.     public void fire()
    2.     {
    3.  
    4.         RaycastHit hit;
    5.         Vector3 targetPoint;
    6.  
    7.         if (animator != null)
    8.             animator.SetTrigger("FireTrigger");
    9.  
    10.         // calculate travel direction of the projectile
    11.         Ray ray = fpsCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
    12.  
    13.         if (Physics.Raycast(ray, out hit))
    14.         {
    15.             targetPoint = hit.point;
    16.         }
    17.         else
    18.         {
    19.             targetPoint = ray.GetPoint(75f);
    20.         }
    21.  
    22.         Vector3 directionWithoutSpread = targetPoint - spawnPoint.position;
    23.         directionWithoutSpread.Normalize();
    24.  
    25.         GameObject currentBullet = Instantiate(bullet, spawnPoint);
    26.         Rigidbody bulletRb = currentBullet.GetComponent<Rigidbody>();
    27.         bulletRb.AddForce(directionWithoutSpread * ShootForce, ForceMode.Impulse);
    28.     }
     
  2. Erenquin

    Erenquin

    Joined:
    Apr 9, 2018
    Posts:
    164
    Ok found the reason:
    Instantiate called like I do here above does not define the position but the parent.
    In my case the parent is child of the weapon, itself a child of the camera.
    GameObject currentBullet = Instantiate(bullet, spawnPoint);

    And Instantiate like below, actually defines a position and no parent.
    As I did not care about the rotation I thought to spare this parameter, but no, it calls another version of Instantiate with a somewhat different behavior:
    GameObject currentBullet = Instantiate(bullet, spawnPoint.position, Quaternion.identity);