Offsetting a Mouse Point Raycast?


I have a math problem I’m just not able to figure out and I was wondering if anyone can suggest a solution.

I have a FPS/Rails shooter game. The bullets are physical mesh models that get fired from the gun. The gun is a gameobject with no mesh and the bullets fire from the guns position.

The crosshair follows the mouse pointer’s position and so the ray gets cast from the camera’s position to the mouse point and the raycast’s hit point is the point used for aiming the gun’s bullets.

What I would like is to be able to move the gun’s position slightly to the right or left of the camera so bullets can be seen better. The problem is when I do this the aim gets skewed because while the bullets will fire from the gun’s position, the hit point is calculated from the camera’s position and the mouse position. This causes the bullets to fire offcenter of the crosshair. This also visually confusing.

So what I’m trying to figure out is how I would fire the bullet from the gun and have the hit point still appear as being centered in the crosshair when the gun is offset from the camera’s position. I made a little illustration to try and show what I’m talking about below.

Also to clarify. By visually interesting / uninteresting, I’m talking about hit this appears to the player while playing the game. When the gun is offset to the left or right the bullets can be seen by the player, but when its centered to the cameras position the bullets always come from the middle of the screen which looks odd.


Use the following code. It gets the position you want to hit and the position you want the bullet to start then gets the direction the bullet should travel using the difference between the two.

void Update() {
    if(Input.GetKeyDown(KeyCode.Mouse0)) {
        Ray ray=camera.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if(Physics.Raycast(ray, out hit)) {
            Vector3 target=hit.point;
            Vector2 offsetMouse=new Vector2(Input.mousePosition.x+x, Input.mousePosition.y+y);
            Vector3 start=camera.ScreenToWorldPoint(offsetMouse);
            Vector3 direction=(target-start).normalized;
            CreateBullet(start, direction);
void CreateBullet(Vector3 startPoint, Vector3 direction) { 
    // make a bullet at start point that flies in direction