Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by TheNachoman180 · Mar 03, 2013 at 07:10 AM · raycastfpsscreenmiddleaccurate

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!

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ByteSheep · Mar 03, 2013 at 07:14 AM 0
Share

Add a raycast script to the camera ins$$anonymous$$d. You can easily adapt your BulletScript code

2 Replies

· Add your reply
  • Sort: 
avatar image
0

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))
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

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?

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image TheNachoman180 · Mar 05, 2013 at 06:36 AM 0
Share

any ideas?

avatar image TheNachoman180 · Mar 06, 2013 at 05:52 AM 0
Share

Anyone have any ideas?

avatar image gfvfubb · Mar 06, 2013 at 05:55 AM 0
Share

There is a working example of this in the Unity Bootcamp demo. Check Solder_Locomotion and the Gun object scripts.

avatar image robertbu · Mar 06, 2013 at 06:29 AM 0
Share

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?

avatar image TheNachoman180 · Mar 08, 2013 at 10:29 AM 0
Share

not using a projectile

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

11 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges