• 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 Hallker · Aug 15, 2013 at 07:47 PM · bulletprojectileweaponwindballistic

Could you advice me why this Gun and Ballistic Script doesn't work?

Hello guys, this is my first question/entry into Unity Answers so if I do anything bad go ahead and tell me. I plan to hang around a lot :)

So I found this script on youtube from user named Muzkaw who made somehow realistic Bullet behavior. He did it in Java Script and I tried to convert it into C# but it doesn't work.

This is code for my Weapon that shoots the "bullet" from "spawnPoint" in direction where is "camera" looking. This script is attached to Gun.

 void Update ()
     {
         if(Input.GetKeyDown("mouse 0"))
         {
             Instantiate(bullet, spawnPoint.transform.position, camera.transform.rotation);
         }
 }

This is code for ballistics, this code should give our bullet some speed, after some time apply gravity to change trajectory, ricochet in case of collision and should be affected by wind. This script is attached to bullet prefab that is spawned by Gun.

 void Start () 
     {
         shotTime = Time.time;
         
         velocity = muzzleSpeed * transform.forward;
     }
     
     // Update is called once per frame
     void Update () 
     {
         lifeTime = Time.time - shotTime;
         
         if(lifeTime>2.5)
         {
             Destroy(gameObject);
         }
         
         //This lane of code is about pushing our projectile forward at velocity speed
         transform.position += transform.forward * Vector3.Magnitude(velocity)*Time.deltaTime;
         
         //This lane of code is about slowing down our projectile because of air friction
         transform.position -= transform.forward * envirFriction * Vector3.Magnitude(velocity)*Time.deltaTime;
         
         //Time squared by two saved in variable
         shotTime2 = Mathf.Pow((Time.time - shotTime),2);
         
         //This lanes of code adds gravity to our projectile in order to change his trajectory
         currentPos = transform.position;
         currentPos.y += (gravity * shotTime2);
         
         //This lane of code is about adding wind force to projectile
         currentPos += WindScript.f * WindScript.s * shotTime2 * windEffect;
         
         //Recalculate current velocity
         velocity = (currentPos - previousPos)/(Time.deltaTime);
         
         //This lane of code is about computing kinetic energy of our projectile
         kineticEnergy = bulletMass * Mathf.Pow(Vector3.Magnitude(velocity),2);
             Debug.Log( kineticEnergy );
         
         //This IF statement prevents problematic instation at 0 posiiton
         if(previousPos == Vector3.zero)
         {
             previousPos = spawnPoint.transform.position;
         }
         
         //Draw a red line for debug
         if((Time.time-shotTime) > 0.001)
         {
             Debug.DrawLine(previousPos, currentPos, Color.red, dur);
         }
         
         if (Physics.Linecast(previousPos, currentPos, out hit, layerMask) && (Time.time - shotTime) > 0.001)
         {
             if (hit.rigidbody)
             {
                 hit.rigidbody.AddForceAtPosition( konstantKe * kineticEnergy * transform.forward, hit.point );
             }
             
             Debug.DrawRay(hit.point,hit.normal*1,Color.green, dur);
             
             contactAngle = Vector3.Angle(transform.forward,hit.normal);
         
             
             if ( contactAngle <= 120.0 && Random.Range(-1,ricochetAmmount)>=0)
             {
                 reflectDirection = Vector3.Reflect(transform.forward,hit.normal);
                 
                 reflectDirection += new Vector3(Random.Range(0,randAngle),Random.Range(-randAngle,randAngle),Random.Range(-randAngle,randAngle));
                 
                 reflectDirection = transform.forward;
                 
                 transform.position = hit.point ;
                 
                 muzzleSpeed = contactAngle + Random.Range(-randSpeed,randSpeed) ;
             }
             
             else
             {
                 Destroy(gameObject);
             }
         }
     }
     
     void FixedUpdate()
     {
         previousPos = transform.position;
     }

And as last one there is this Wind Script where wind changes it's speed and direction over time. Ballistic script has reference to this one.

 void Start () 
     {
         targetAngle = new Vector3(Random.Range(-20,20),Random.Range(-360,360),0);
         
         windForce = Random.Range(0,maxWindForce);
     }
     
     // Update is called once per frame
     void Update () 
     {
         Rand();
         
         Quaternion newRot = transform.rotation;
         
         newRot = Quaternion.Euler(targetAngle);
         
         transform.rotation = Quaternion.Slerp(transform.rotation, newRot, speed*Time.deltaTime);
         
         Vector3 localSca = transform.localScale;
         
         localSca.z = Mathf.Lerp(transform.localScale.z, windForce, speed*Time.deltaTime);
     
     //Debug.Log(windForce);
     
         f = transform.forward ;
         
         s = transform.localScale.z ;
     }
     
     void Rand ()
     {
         waitTime = Random.Range(windTimeVar,2*windTimeVar);
         
         targetAngle += new Vector3(Random.Range(-dWindx,dWindx),Random.Range(-dWindy,dWindy),0);
         
         targetAngle.x=Mathf.Clamp(targetAngle.x,-20,20);
         
         windForce += Random.Range(-dWindForce,dWindForce);
         
         windForce = Mathf.Clamp(windForce,0,maxWindForce);
         
         Invoke("Wait for (waitTime) seconds", waitTime);
     }

I welcome any advice that you can give me. I think I did some mistakes during converting from JavaScript to C# but I can't locate where. If this is too much of work don't hesitate to send me to hell. :)

This is the video where I found original JavaScript in description. http://www.youtube.com/watch?v=oxZUNViLDUw

EDIT: I forgot post what didn't worked, gun is working correctly I guess but bullet is not dropping with gravity and since I set bullet to draw some debug I can see there is some weird behaviour during the flight. Also bullet is not affected by wind at all.

For some reason it just fly straight. I am quite not sure why, but debug line is thin at first and then it get's wider like if the bullet builds up some speed in mid-air.

Thanks for your advices ahead P.S. Sorry for crappy English it's not my primary language.

Comment
Add comment · Show 2
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 YoungDeveloper · Aug 15, 2013 at 07:49 PM 0
Share

What exactly didn't work, post the error.

avatar image Hallker · Aug 15, 2013 at 08:01 PM 0
Share

I added it to the end of the post. Thanks for asking. And no errors in console so far.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Muzkaw · Aug 15, 2013 at 09:52 PM

Hi again, I managed to get to the thread :p

Look out between lines 27 and 32 :

 currentPos = transform.position;
 currentPos.y += (gravity * shotTime2);
  
 //This lane of code is about adding wind force to projectile
 currentPos += WindScript.f * WindScript.s * shotTime2 * windEffect;

You don't modify anymore you're bullet position but the currentPos variable ! You need to add this line of code after computing gravity : transform.position = currentPos ;

Hopefully, your bullet should drop !

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 Hallker · Aug 16, 2013 at 05:43 AM 0
Share

Ok, thanks for advice. I'll try it once I get home. It seems so obvious now. Thank you.

avatar image Hallker · Aug 17, 2013 at 10:40 PM 0
Share

Ok I must have screwed this one up a big time. Bullet is going up ins$$anonymous$$d of down. I really don't have and idea why... I'll try to rework it in next few days.

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

17 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 avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Best way to make multiplayer projectiles and enemy shooting player (discussion) ? 0 Answers

Shooting multiple bullets 2 Answers

Click button to fire weapon. 3 Answers

how to make hud with weapon script? 0 Answers

How to implement wind for a projectile motion? 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