- Home /
Solved: Problem with shooting script
So I am using a raycast for the shooting in my FPS, which is working great, but I have run into a small problem. The raycast is not cast from the actual gun object's position, but from a muzzle object, that is set in the middle of the player object(which is the FPS Controller prefab). A crosshair is drawn directly in the middle of the screen. The issue is that the muzzle object is not lined up perfectly with the crosshair, so depending on which angle the player is facing, the raycast hits close to the crosshair, but not directly at its center. Basically what I want is either a way to make the muzzle object's forward location be set to exactly the center of where the crosshair texture is draw, or (preferably) a way to make the raycast start at the muzzle object and extend to the center of the texture. I am not sure how to go about doing this. Any advice or info would be much appreciated. The code I am using is at the bottom of this post. Thanks for your time!
if (Physics.Raycast(muzzle.transform.position, dir, hit, range))
{
var objectHit : String = hit.collider.gameObject.tag;
print(objectHit);
var cloneEffect = PrefabUtility.InstantiatePrefab(hitParticles);
cloneEffect.transform.position = hit.point;
cloneEffect.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
if (hit.rigidbody)
hit.rigidbody.AddForceAtPosition(force*dir, hit.point);
}
GUI.DrawTexture(new Rect(Screen.width / 2, Screen.height / 2, crosshair.width, crosshair.height), crosshair);
Answer by vinod.kapoor · Oct 20, 2012 at 09:23 AM
you are not drawing the Crosshair at the center of the image
you have written :
GUI.DrawTexture(new Rect(Screen.width / 2, Screen.height / 2, crosshair.width, crosshair.height), crosshair);
replace it with :
GUI.DrawTexture(new Rect(Screen.width / 2-crosshair.width /2, Screen.height / 2 - crosshair.height/2,, crosshair.width, crosshair.height), crosshair);
Oh, ok makes total sense now. The origin of the image is the top-left corner, so it is placing the top left corner at the center of the screen, correct? Thanks for your help!!