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
1
Question by NewGuy · Jan 28, 2013 at 12:33 PM · fpsaimingcrosshairbullets

FPS Bullets Generic Solution. How?

Im designing a game to learn... Im a hobbyist.

The game is very simple the screen will show you objects and you shoot it.

Thats been said. What i need to achive is this.

1- FPS moves around (Solved using FPS script with its mouse controller script) 2- Add Cross-hair in the screen for aiming (Solved using the following code) I added it to the FPS Camera

     var crosshairTexture : Texture2D;
     var position : Rect;
     static var OriginalOn = true;
      
     function Start()
     {
     position = Rect((Screen.width - crosshairTexture.width) / 2, (Screen.height -
     crosshairTexture.height) /3, crosshairTexture.width, crosshairTexture.height);
     }
      
     function OnGUI()
     {
     if(OriginalOn == true)
     {
     GUI.DrawTexture(position, crosshairTexture);
     }
     }



3- Bullets shoot i used the bellow script

 var fireRate : float = 4.0;
 private var nextFire : float = 0.0;
 var prefabBullets:Transform;
 var shootForce: float;
     function Start(){   
         }                          
     function Update () {
     
         if (Input.GetMouseButtonDown(0) && IsOkToShoot()) {
             Shoot(); //Shoot when conditions are met
             var instanceBullet = Instantiate(prefabBullets, transform.position, Quaternion.identity);
             instanceBullet.rigidbody.AddForce(transform.forward * shootForce);
             Destroy (instanceBullet.gameObject, 2); 
         }
     }
      
     function IsOkToShoot () : boolean {
     //Here we check that current time exceeds nextFire
     var itsOk : boolean = false;
     
         if (Time.time>nextFire) {
             //Debug.Log(Time.time);
             nextFire = Time.time + fireRate;
             itsOk = true;
         }
     return itsOk;
     }
      
     function Shoot () {
 audio.Play();
     }



I have few questions.....

1- How to make the bullets Always go at the Cross-hair ? 2- How to Get the objects name that the bullets hit ?

Any help it would be great thank you all....

Comment
Add comment
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

2 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by arosellisp · Jan 28, 2013 at 01:13 PM

Hello There,

Generally in FPS games, the bullets fired from your gun are not real 3d projectiles that hit your target, but rather just a graphical asset ,there are exceptions to this, but those involve a whole physics solution for the projectile, involving wind forces, for example.

In this case, I would recommend using the most usual solution. To achieve that, instead of instatiating a bullet prefab and adding force to it, simply cast a Raycast from your camera to check if you did hit something.

Unity's docs on this : Original Docs

Here is a small example on achieving this:

  1. LayerMask : Create a Layer for all the objects that can be hit

  2. Camera.main.ScreenPointToRay() Will create a ray going for the FPS camera to the crosshair ( or you could just use the Input.mousePosition )


    var hittableObjects : LayerMask; var ray = Camera.main.ScreenPointToRay (crossHairPosition); var hit : RaycastHit; var range : float = 100;

    if (Physics.Raycast (ray, hit, range, hittableObjects)) { // You have hit something }

Hope it helps.

Comment
Add comment · Show 2 · 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 NewGuy · Jan 28, 2013 at 08:33 PM 0
Share

Thanks arosellisp....

Thats changes everything...... :-( After reading for sometime i made solution with a help os a script was posted in the Unity3D Answers.

I need to tweak it then i will post it for improvement to the answer from the Community.....

avatar image arosellisp · Jan 29, 2013 at 01:06 AM 0
Share

I'm glad to hear it, hope it all works well. All in all, it should be easier to build using the raycast solution, ins$$anonymous$$d of making a bullet object that has to check it's collision and everything (since problems can arise with physics and everything).

avatar image
0

Answer by NewGuy · Jan 30, 2013 at 06:13 AM

Hear is a simple code But it still need alot of tweeking Such as

-When object is clicked on a particulare animation of that object works.. - Sound for shoot and for reload (I tried playing 2 sound but its just not working. I will check with Unity3d Answers.) - ..etc

New Updated CODE Please Comment on it for improvement.....

 #pragma strict
 @script RequireComponent(AudioSource)
 @script RequireComponent(AudioSource)
 var animatedObject1 : GameObject;
 var animatedObject2 : GameObject;
 
 var Range : float = 50;
 var Force : float = 400;
 
 var fireRate : float = 2.0; //The rate of fire for the gun
 private var nextFire : float = 0.0; //When the next fire is ok to shoot off
 
 public var itsOk : boolean = true;
 
 var audio1: AudioSource;
 var audio2: AudioSource;
 
 
 function Start(){
     var aSources = GetComponents(AudioSource);
     audio1 = aSources[0];
     audio2 = aSources[1]; 
 }
 
 function Update () {
         if (Input.GetButtonDown("Fire1") && itsOk && IsOkToShoot()){
             audio2.Play();
             ShootGun();
             itsOk = false;
         }
 
         if(Input.GetButtonDown("Fire2") && itsOk == false){
             ReloadLogic();
             itsOk = true;
         }
 }
 function  ReloadLogic() : boolean{
     var itsOk : boolean = false;
     PlayReloadAudio ();
     ReloadDelay();// This Does not seem to work therfore i used IsOkToShoot()
     itsOk = true;
             
     return itsOk;
 }
 
 function ReloadDelay(){
 
 yield WaitForSeconds(1.5);
 
 }
 
 function ShootGun (){
 
     var Hit: RaycastHit;
     var DirectionRay = transform.TransformDirection(Vector3.forward);
     
     Debug.DrawRay(transform.position, DirectionRay * Range, Color.blue );
     
     if(Physics.Raycast(transform.position, DirectionRay, Hit, Range)){
     
         if(Hit.rigidbody){
             Hit.rigidbody.AddForceAtPosition(DirectionRay * Force, Hit.point);
              
              var distanceToGround = Hit.distance;
              var HitName = Hit.transform.gameObject.name;
              var HittedObjectName = Hit.transform.gameObject;
              // Some Debuging
              print(distanceToGround);
              print(HitName);
              print(animatedObject1.name); 
              
              if(animatedObject1.name == HitName){ 
                  animatedObject1.animation.Play("die");
 
              }else if(animatedObject2.name == HitName){
                  animatedObject2.animation.Play("diehard"); 
  
              }
              
              
              Destroy(HittedObjectName, 5);
         }
     }
 }
 
    function IsOkToShoot () : boolean {
     //Here we check that current time exceeds nextFire
     var itsOk : boolean = false;
     
         if (Time.time>nextFire) {
             //Debug.Log(Time.time);
             nextFire = Time.time + fireRate;
             itsOk = true;
         }
     return itsOk;
     }
 
 function PlayShootAudio (){
     audio2.Play();
 }
 function PlayReloadAudio (){
 audio1.Play();
 }
Comment
Add comment · Show 1 · 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 NewGuy · Jan 30, 2013 at 01:42 PM 0
Share

I hope someone could give me a comment on the animation $$anonymous$$ethod is correct or there is a better way.. Line 75..etc

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

10 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

Related Questions

Aiming Down Sights Problem 2 Answers

FPS Tutorial problem 1 Answer

Fps Aiming Script help 2 Answers

colliding bullets 2 Answers

spraying bullets 3 Answers


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