- Home /
Raycasting Accurately with gun
hello. I have made a gun in unity and i have been following eteeskis fps tutorials and i have come into a problem. My gun isnt accurately firing. How would i make it so it raycasts in exactly the middle of the screen regardless of where the gun is? (Instead of having a gameobject on the end of the barrel shooting innacurately.
My Gunscript:
var beingHeld : boolean = false;
var outsideBox : GameObject;
@HideInInspector
var countToThrow : int = -1;
@HideInInspector
var playerTransform : Transform;
@HideInInspector
var playerMovementScript : PlayerMovementScript;
@HideInInspector
var cameraObject : GameObject;
@HideInInspector
var targetXRotation : float;
@HideInInspector
var targetYRotation : float;
@HideInInspector
var targetXRotationV : float;
@HideInInspector
var targetYRotationV : float;
var rotateSpeed : float = 0.3;
var holdHeight : float = -0.5;
var holdSide : float = 0.5;
var ratioHipHold : float = 1;
var hipToAimSpeed : float = 0.1;
@HideInInspector
var ratioHipHoldV : float;
var aimRatio : float = 0.5;
var zoomAngle : float = 30;
var firespeed : float = 15;
@HideInInspector
var waitTilNextFire : float = 0;
var bullet : GameObject;
var bulletSpawn : GameObject;
var shootSoundObject : GameObject;
var shootAngleRandomizationAiming : float = 5;
var shootAngleRandomizationNotAiming : float = 15;
var recoilAmount : float = 0.5;
var recoilRecoverTime : float = 0.2;
@HideInInspector
var currentRecoilZPos : float;
@HideInInspector
var currentRecoilZPosV : float;
var bulletSound : GameObject;
var muzzleFlash : GameObject;
var flashEmitter : GameObject;
var gunBobAmountX : float = 0.5;
var gunBobAmountY : float = 0.5;
var currentGunBobX : float;
var currentGunBobY : float;
var gunModelObjects : GameObject[];
var reloading : boolean = false;
var reloadAnimation : Animation;
var reloadAnimationString : String;
var clipSize : int = 13;
var currentClip : int = 4;
var maxExtraAmmo : int = 52;
var currentExtraAmmo : int = 52;
var ammoType : int = 0;
var bulletHudTexture : Texture;
var ammoCountRect : Rect = Rect(25, 25, 50, 25);
var ammoStartX : int = 100;
var ammoY : int = 25;
var ammoSize : Vector2 = Vector2(10, 25);
var ammoSpacing : int = 4;
var gunIconRect : Rect = Rect(25, 50, 50, 25);
var gunIconTexture : Texture;
var Auto : boolean;
function Awake()
{
countToThrow = -1;
playerTransform = GameObject.FindWithTag("Player").transform;
playerMovementScript = GameObject.FindWithTag("Player").GetComponent(PlayerMovementScript);
cameraObject = GameObject.FindWithTag("MainCamera");
}
function LateUpdate ()
{
if (currentClip > clipSize)
currentClip = clipSize;
if (currentExtraAmmo > maxExtraAmmo)
currentExtraAmmo = maxExtraAmmo;
if (currentClip < 0)
currentClip = 0;
if (currentExtraAmmo < 0)
currentExtraAmmo = 0;
if (beingHeld)
{
if (!reloading && Input.GetButtonDown("Reload")&& currentClip < clipSize && currentExtraAmmo > 0)
{
reloading = true;
reloadAnimation.Play(reloadAnimationString);
}
if (!reloading && Input.GetButtonDown("Fire1")&& currentClip == 0 && currentExtraAmmo > 0)
{
reloading = true;
reloadAnimation.Play(reloadAnimationString);
}
if (reloading && !reloadAnimation.IsPlaying(reloadAnimationString))
{
if (currentExtraAmmo >= clipSize - currentClip)
{
currentExtraAmmo -= clipSize - currentClip;
currentClip = clipSize;
}
if (currentExtraAmmo < clipSize - currentClip)
{
currentClip += currentExtraAmmo;
currentExtraAmmo = 0;
}
reloading = false;
}
for(var modelObject : GameObject in gunModelObjects)
{
modelObject.layer = 8;
}
rigidbody.useGravity = false;
outsideBox.GetComponent(Collider).enabled = false;
currentGunBobX = Mathf.Sin(cameraObject.GetComponent(MouseLookScript).headbobStepCounter) * gunBobAmountX * ratioHipHold;
currentGunBobY = Mathf.Cos(cameraObject.GetComponent(MouseLookScript).headbobStepCounter * 2) * gunBobAmountY * -1 * ratioHipHold;
var holdMuzzleFlash : GameObject;
var holdSound : GameObject;
if (Auto)
{
if (Input.GetButton("Fire1")&& currentClip > 0 && !reloading)
{
if (waitTilNextFire <= 0)
{
currentClip -=1;
if (bullet)
Instantiate(bullet,bulletSpawn.transform.position, bulletSpawn.transform.rotation);
if (bulletSound)
holdSound = Instantiate(bulletSound,shootSoundObject.transform.position, shootSoundObject.transform.rotation);
if (muzzleFlash)
holdMuzzleFlash = Instantiate(muzzleFlash,flashEmitter.transform.position, flashEmitter.transform.rotation);
targetXRotation -= (0.1) * Mathf.Lerp(shootAngleRandomizationAiming, shootAngleRandomizationNotAiming, ratioHipHold);
currentRecoilZPos -= recoilAmount;
waitTilNextFire = 1;
}
}
}
else if (!Auto)
{
if (Input.GetButtonDown("Fire1")&& currentClip > 0 && !reloading)
{
if (waitTilNextFire <= 0)
{
currentClip -=1;
if (bullet)
Instantiate(bullet,bulletSpawn.transform.position, bulletSpawn.transform.rotation);
if (bulletSound)
holdSound = Instantiate(bulletSound,shootSoundObject.transform.position, shootSoundObject.transform.rotation);
if (muzzleFlash)
holdMuzzleFlash = Instantiate(muzzleFlash,flashEmitter.transform.position, flashEmitter.transform.rotation);
targetXRotation -= (0.1) * Mathf.Lerp(shootAngleRandomizationAiming, shootAngleRandomizationNotAiming, ratioHipHold);
currentRecoilZPos -= recoilAmount;
waitTilNextFire = 1;
}
}
}
waitTilNextFire -= Time.deltaTime * firespeed;
if(holdSound)
holdSound.transform.parent = transform;
if(holdMuzzleFlash)
holdMuzzleFlash.transform.parent = transform;
currentRecoilZPos = Mathf.SmoothDamp( currentRecoilZPos, 0, currentRecoilZPosV, recoilRecoverTime);
cameraObject.GetComponent(MouseLookScript).currentTargetCameraAngle = zoomAngle;
if (Input.GetButton("Fire2")&& !reloading)
{
cameraObject.GetComponent(MouseLookScript).currentAimRatio = aimRatio;
ratioHipHold = Mathf.SmoothDamp(ratioHipHold, 0, ratioHipHoldV, hipToAimSpeed);
}
if (Input.GetButton("Fire2") == false || reloading)
{
cameraObject.GetComponent(MouseLookScript).currentAimRatio = 1;
ratioHipHold = Mathf.SmoothDamp(ratioHipHold, 1, ratioHipHoldV, hipToAimSpeed);
}
transform.position = cameraObject.transform.position + (Quaternion.Euler(0,targetYRotation,0) * Vector3(holdSide * ratioHipHold + currentGunBobX, holdHeight * ratioHipHold + currentGunBobY, 0)+ Quaternion.Euler(targetXRotation, targetYRotation, 0)* Vector3(0,0,currentRecoilZPos));
targetXRotation = Mathf.SmoothDamp(targetXRotation, cameraObject.GetComponent(MouseLookScript).xRotation, targetXRotationV, rotateSpeed);
targetYRotation = Mathf.SmoothDamp(targetYRotation, cameraObject.GetComponent(MouseLookScript).yRotation, targetYRotationV, rotateSpeed);
transform.rotation = Quaternion.Euler(targetXRotation, targetYRotation, 0);
}
else
{
rigidbody.useGravity = true;
outsideBox.GetComponent(Collider).enabled = true;
countToThrow -= 1;
for(var modelObject : GameObject in gunModelObjects)
{
modelObject.layer = 0;
}
if (countToThrow == 0)
rigidbody.AddRelativeForce(0, playerMovementScript.throwGunUpForce, playerMovementScript.throwGunForwardForce);
if (Vector3.Distance(transform.position, playerTransform.position) < playerMovementScript.distToPickUpGun && Input.GetButtonDown("Use Key") && playerMovementScript.waitFrameToSwitchGuns <- 0)
{
playerMovementScript.currentGun.GetComponent(GunScript).beingHeld = false;
playerMovementScript.currentGun.GetComponent(GunScript).countToThrow = 2;
playerMovementScript.currentGun = gameObject;
beingHeld = true;
targetYRotation = cameraObject.GetComponent(MouseLookScript).yRotation -180;
playerMovementScript.waitFrameToSwitchGuns = 2;
}
}
}
function OnGUI()
{
if (beingHeld)
{
for(var i : int = 1; i <= currentClip; i++)
{
GUI.DrawTexture(Rect(ammoStartX - ((i - 1) * (ammoSize.x + ammoSpacing)), ammoY, ammoSize.x, ammoSize.y), bulletHudTexture);
}
GUI.Label(ammoCountRect, currentExtraAmmo.ToString());
GUI.DrawTexture(gunIconRect, gunIconTexture);
}
}
My BulletScript:
var maxDist : float = 1000000000;
var decalHitWall : GameObject;
var floatInFrontOfWall : float = 0.00001;
var damage : float = 10;
var force : float = 0.00000001;
function Update ()
{
var hit : RaycastHit;
var bulletDirection = transform.forward;
if(Physics.Raycast(transform.position, transform.forward, hit, maxDist))
{
if (decalHitWall && hit.transform.tag == "LevelParts")
Instantiate(decalHitWall, hit.point + (hit.normal * floatInFrontOfWall), Quaternion.LookRotation(hit.normal));
}
if (hit.rigidbody)
hit.rigidbody.AddForceAtPosition(force * bulletDirection, hit.point);
Destroy(gameObject);
}
any ideas?
if you need anything else just ask!
Add a raycast script to the camera ins$$anonymous$$d. You can easily adapt your BulletScript code
Answer by robertbu · Mar 03, 2013 at 08:40 AM
In order to project from the center, just use the camera position and the camera forward in the Raycast:
if(Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, hit, maxDist))
Answer by TheNachoman180 · Mar 04, 2013 at 06:12 AM
i replaced
if(Physics.Raycast(transform.position, transform.forward, hit, maxDist))
with
if(Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, hit, maxDist))
and its still inacurate. I also created a bulletspawn GameObject on the camera and set it to 000 and it is still inacurate. Can someone explain this further?
There is a working example of this in the Unity Bootcamp demo. Check Solder_Locomotion and the Gun object scripts.
Inaccurate in what way? If you are using a projectile, it will drop due to gravity. Also how did you handle the change in the raycast point. Did you point your bullet at the hit point (transform.LookAt(hit.point)) before adding force?
Your answer
Follow this Question
Related Questions
Raycast to middle screen doesn't work 1 Answer
Why does this script I got from the Unity Document site does not work? 1 Answer
Multiplayer FPS Bullets: should they be rigid bodies or raycast? 1 Answer
How to implement gun accuracy/spread with raycast 1 Answer
How make Raycast Aim to Crosshair? 1 Answer