0

I have been making a first person game called "shoot the ball into the bin". The camera is in a cylinder as a player also the cylinder has collision.

I have been struggling with the main driver of the game. Like in most first person shooter games, you shoot out from the center point of the camera or the cursor.

I have trouble replicating that. The code I have so far for the shooting is:

Instantiate(prefab, new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y, Camera.main.transform.position.z), Camera.main.transform.rotation);

(Credits to @derHugo for helping me instantiate a prefab)

But that just spawns it on top of the player, not in front of it. How do I make it shoot away from the player, but also in front of the player, not on top.

2 Answers2

2

In order to spawn in front of that position simply use

// Already reference this via the Inspector if possible
[SerializeField] private Camera _camera;
// Adjust how far in front of the camera the object should spawn
[SerializeField] private float distance;

private void Awake ()
{
    // otherwise get it ONCE
    if(!_camera) _camera = Camera.main;
}

And then simply add an offset in the direction of Transform.forward of the camera like

Instantiate(prefab, _camera.transform.position + _camera.transform.forward * distance, _camera.transform.rotation);
derHugo
  • 83,094
  • 9
  • 75
  • 115
0

so it seems when you instantiate the bullets, you are spawning them directly on the position of the camera. You should adjust those values so that it spawns in the center of the screen. To do so, you should divide the y position by 2 or 1.5 depending on how high up the gun is from the ground. Then change the z so that the bullets pushed further in front of the player.

Instantiate(prefab, new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y / 2, Camera.main.transform.position.z + somearbitraryvalue), Camera.main.transform.rotation);

Next, to get give the bullets a velocity, you should create a separate script for the bullet prefab that is in charge of moving the bullets.

    public Rigidbody2D bullet;
bullet = GetComponent<Rigidbody2D>()

void Update(){
bullet.velocity = new Vector 3(0,0,1)
}

Hope this answer helps!