Bullet hits the object not in the center of the screen

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;
        clone.velocity = transform.TransformDirection(Vector3.forward * speed);


I think the problem you have is that the tip of the gun is off centre, and the bullet is going straight forward from this off centred point.

A solution would be to use ViewportPointToRay to get the centre of the screen and then calculate the vector towards this point instead of Vector3.forward.


var centre = new Vector3(0.5f, 0.5f, 0f);

var ray = Camera.main.ViewportPointToRay(centre);

clone.velocity = ray.direction * speed;

To help debug you can also use this to show the ray in your editor’s scene

Debug.DrawRay(ray.origin, ray.direction * 500, Color.red, 5);