I am making a FPS. I have a rocket launcher firing a projectile. It currently fires from the muzzle in the direction the launcher is pointing to. This makes it hard to aim at anything. I would like for the projectile to go to the crosshair in the middle of the screen instead. I think i could use raycast but im not sure how to make that work with what i have currently. Is there an easy and quick solution without having to change to much? I am using C# but i think i could work with java-script.
public GameObject launchPosition;
public Rigidbody projectilePrefab;
float projectileSpeed= 30.0f;
Rigidbody instantiatedProjectile = Instantiate (projectilePrefab, launchPosition.transform.position, launchPosition.transform.rotation)as Rigidbody;
fireLauncherAnim.animation.Play("firefromhip");
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0.0f,0.0f, projectileSpeed));
Physics.IgnoreCollision(instantiatedProjectile.collider, GameObject.FindWithTag("Player").transform.root.collider);
I’m assuming that you have a character controller or some other sort of rotation script on the camera. And there is a crosshair in the middle that you want to use for targeting. If this is the setup, you can just create an empty game object just in front of the camera and attach the script above to that game object and you will shooting projectiles from the center of the screen. Depending on your game, there is a potential problem. If you projectiles are under the influence of gravity the projectiles will fall some distance between the time they are created and the time they impact, so it will typically impact below your target.
One solution is to turn off gravity for your projectile. There are other more complicated solutions.
I am still not quite sure what your issue is, you should be able to just automatically instantiate your rockets to shoot from your character as long as the gameObject your rocket script is attached to can in fact rotate?
It does not look like you are using Quarternion.identity in your instantiate? Try something like this might help:
instantiateBullet = (Rigidbody)Instantiate(bullet, transform.position, Quaternion.identity);
I also use something like this for the projectile because it allows physics to work:
instantiateBullet.AddForce(transform.forward *bulletVelocity);
If you have both those set up it should work automatically as long as the gameObject it is attached to can in fact rotate. Quaternion.Identity will ensure that the projectile will come from the position you originally set it to, in relation to your new rotation.