STUCK! Firing a simple sphere from below the camera at crosshair in the centre of the screen, with or without raycast.
I have a game that spawns "enemies" within a sphere around the camera, the player moves the camera to target and simply presses the screen to fire. For now my "ammo" is simply a sphere and for visual purposes the object I'm firing from is a sphere located below the camera. the "ammo" should fire from the "cannon" below the camera directly towards the crosshair and hit whatever target is in the crosshair.
With some online help this is how my crosshair is generated:
if(Time.timeScale != 0)
{
if(crosshairTexture!=null)
GUI.DrawTexture(new Rect((Screen.width-crosshairTexture.width*crosshairScale)/2 ,(Screen.height-crosshairTexture.height*crosshairScale)/2, crosshairTexture.width*crosshairScale, crosshairTexture.height*crosshairScale),crosshairTexture);
else
Debug.Log("No crosshair texture set in the Inspector");
}
And currently this is how my "Cannon" works
if ( Input.GetButton("Fire1") && Time.time > mNextFire){
mNextFire = Time.time + mFireRate;
Rigidbody projectile= (Instantiate (ammo, gameObject.transform.position, Quaternion.identity)).GetComponent<Rigidbody>();
projectile.AddForce (projectile.transform.forward * mHitForce);
}
Then on the ammo, I have this:
int x = Screen.width / 2;
int y = Screen.height / 2;
transform.LookAt(new Vector3(x, y));
but it is horribly inaccurate, I had to move the canon around so it appears to be firing from below the camera, the speed/velocity is off and it barely hits what's being aimed at. It also often appears to go through the cross hair but doesn't collide with the target. I know it's not the target cause if I move the canon around a bit and keep the target still, it hits, the target takes damage, life bar decreases and the "ammo"that hit it "disappears".
I know questions like this are all over the internet however none of them describe my problem, and the ones I found somewhat similar have no solutions. After days of frustration I decided to ask the question here, I just started unity last week so I apologise in advance if my problem seems silly.
Also, I've been seeing a lot of things with raycast, I found this script that projected a yellow laser towards the centre of the screen;
void Update()
{
int x = Screen.width / 2;
int y = Screen.height / 2;
Ray ray = camera.ScreenPointToRay(new Vector3(x, y));
Debug.DrawRay(ray.origin, ray.direction * 1000, new Color(1f,0.922f,0.016f,1f));
}
it worked perfectly and projected the laser right to the centre but what am I supposed to do with it afterwards? how do I make the projectile follow it? I'd really appreciate the help. Thank you!