0
\$\begingroup\$

When player shoot, the bullet fly to the center of the screen. But if player stay too close to some object, then bullet hits it not in the center, because it flies from the gun on the right side of the screen. How can I fix this?

 public Rigidbody projectile;
 public int speed = 50;
 public Transform startBulletPosition;

 void Update()
 {
     if (Input.GetButtonDown("Fire1"))
     {
         Rigidbody clone;
         clone = Instantiate(projectile, startBulletPosition.position, transform.rotation) as Rigidbody;
         var centre = new Vector3(0.5f, 0.5f, 0f);
         var ray = Camera.main.ViewportPointToRay(centre);
         clone.velocity = ray.direction * speed;
     }
 }

enter image description here

Edit 1 enter image description here

\$\endgroup\$
2
  • \$\begingroup\$ If you're very close to a wall, then, wouldn't this be expected behavior? You're not shooting out of the center of the view, it's shooting from the gun. \$\endgroup\$
    – House
    Sep 12, 2017 at 17:28
  • \$\begingroup\$ @MichaelHouse You are right, but it is the same on the pretty big distance like on the new screenshot \$\endgroup\$ Sep 12, 2017 at 17:34

1 Answer 1

3
\$\begingroup\$

Right now your camera center and your bullet trajectory will never meet. You're using what is essentially transform.forward from the camera and using the gun as the starting point, your bullet will always be offset from the center by the same distance as the gun is from the camera.

Regardless, you should probably do it a bit differently, because always aiming at the center of the screen isn't going to work as you want it to.

Instead, cast a ray from the center of the camera, that ray will hit an object in the scene (or reach some maximum distance). Now get the vector between your gun and the hit point (or maximum distance point). Then either direct your bullet along that vector. You can also rotate the player's gun to align with the firing direction.

This essentially changes the aim of the gun based on the distance of the object it's firing at.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .