Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 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 /
  • Help Room /
avatar image
0
Question by doug-in-a-box · Sep 12, 2016 at 01:13 PM · scripting problemcannon

how to make this script shoot when button pressed

hey, so I have this old script that way to complex for what I need. Iv tried to simplify it but I'm struggling. what its setup to do is to find a target and direct the cannon to that target, which is the part that i don't want. i just need it to fire the cannon ball when the buttons pressed and still have the rest of the options like reaction time, recharge time and initial velocity. I'm new to coding so any help would be appreciated

using UnityEngine;

[AddComponentMenu("Exploration/Cannon")] public class Cannon : MonoBehaviour { // Cannonball prefab public GameObject cannonballPrefab;

 // Initial velocity applied to the cannon ball's rigidbody
 public float initialVelocity = 15f;

 // Maximum pitch that can be applied to each shot
 public float maxPitch = 25f;

 // Maximum angle at which the cannon is able to fire
 public float maxYaw = 45f;

 // The firing direction will have this much deviation in degrees
 public float maxAimDeviationAngle = 5f;

 // Maximum possible delay that the cannon will fire after pressing the 'fire' button
 public float reactionTime = 0.2f;

 // How long it takes for the cannon to recharge
 public float rechargeTime = 2f;

 Transform mTrans;
 GameShip mStats;
 float mFireTime = 0f;
 float mRechargeTime = 0f;
 Collider[] mColliders;
 Vector3 mFiringDir;
 float mFiringPitch = 0f;
 float mMaxRange = 1f;

 /// <summary>
 /// Calculated maximum range of the cannon based on max pitch and initial velocity.
 /// </summary>

 public float maxRange { get { return mMaxRange; } }

 /// <summary>
 /// Helper function that calculates the cannon's maximum firing range.
 /// </summary>

 float CalculateMaxRange ()
 {
     // Vertical velocity can be calculated using the pitch and initial full velocity:
     float velocity = Mathf.Sin(Mathf.Deg2Rad * maxPitch) * initialVelocity;

     // This is how long it will take the fired cannon ball to reach the sea level
     float time = -velocity / (0.5f * Physics.gravity.y);

     // Now let's calculate the distance traveled horizontally in the same amount of time
     return Mathf.Cos(Mathf.Deg2Rad * maxPitch) * initialVelocity * time;
 }

 /// <summary>
 /// Cache the transform and the ship controlling this cannon.
 /// </summary>

 void Start ()
 {
     mTrans = transform;
     mStats = GameShip.Find(mTrans);

     // Calculate the cannon's maximum range
     mMaxRange = CalculateMaxRange();

     if (mStats != null)
     {
         // Ship stats found -- use it as root node
         mColliders = mStats.GetComponentsInChildren<Collider>();
     }
     else
     {
         // No ship stats present -- see if there is a rigidbody that can be used as root
         Rigidbody rb = Tools.GetRigidbody(mTrans);
         mColliders = (rb != null) ? rb.GetComponentsInChildren<Collider>() : GetComponentsInChildren<Collider>();
     }
 }

 /// <summary>
 /// Fire the cannon when ready.
 /// </summary>

 void Update()
 {
     float time = Time.time;

     // We're ready to fire -- fire the cannon
     if (mFireTime != 0f && mFireTime <= time)
     {
         // Recharge time varies from 80% to 120% of the intended duration just to add variety
         mRechargeTime = time + rechargeTime * Mathf.Lerp(0.8f, 1.2f, Random.value);
         mFireTime = 0f;

         // Create the cannon ball
         if (cannonballPrefab != null)
         {
             // Instantiate the prefab
             GameObject go = Instantiate(cannonballPrefab, mTrans.position, mTrans.rotation) as GameObject;

             // Ensure that the newly instantiated object's collider won't collide with our colliders
             if (mColliders != null)
             {
                 Collider col = go.GetComponent<Collider>();

                 if (col != null)
                 {
                     foreach (Collider c in mColliders)
                     {
                         Physics.IgnoreCollision(c, col);
                     }
                 }
             }

             // It's usually a good idea to know who fired the cannon ball
             Cannonball cb = go.GetComponent<Cannonball>();
             if (cb != null) cb.owner = mStats.gameObject;

             // Rigidbody is generally expected to be present
             Rigidbody rb = go.GetComponent<Rigidbody>();

             if (rb != null)
             {
                 Vector2 deviation = Vector2.zero;

                 // Deviate the aim a little
                 if (maxAimDeviationAngle > 0f)
                 {
                     deviation = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));
                     deviation.Normalize();
                     deviation *= maxAimDeviationAngle;
                 }

                 // Calculate the initial velocity
                 Quaternion firingDir = Quaternion.LookRotation(mFiringDir);
                 Vector3 vel = (firingDir * Quaternion.Euler(-mFiringPitch + deviation.x, deviation.y, 0f)) *
                     Vector3.forward * initialVelocity;

                 // NOTE: For physics-accurate results we should append the ship's velocity as well,
                 // but this makes the auto-aiming logic fail unless the ship isn't moving.
                 rb.velocity = vel;
             }
             else
             {
                 Debug.LogWarning("The cannon ball is missing its rigidbody");
             }
         }
     }
 }

 /// <summary>
 /// Start the firing process.
 /// </summary>

 public void Fire (Vector3 dir, float distance)
 {
     float time = Time.time;

     if (mRechargeTime < time && mFireTime == 0f)
     {
         Vector3 cannonDir = mTrans.rotation * Vector3.forward;

         // We only want this cannon to fire if the specified direction is close enough.
         // It wouldn't make sense to fire guns that are on the opposite side of the ship.
         if (Vector3.Angle(dir, cannonDir) < maxYaw)
         {
             mFireTime = time + Random.value * reactionTime;
             mFiringDir = dir;
             mFiringPitch = Mathf.Clamp01(distance / mMaxRange) * maxPitch;
         }
     }
 }

}

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

0 Replies

· Add your reply
  • Sort: 

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

82 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 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 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 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 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

Unexpected symbol 'return' in class, struct, or interface member declaration 3 Answers

GameObject.FindGameObjectsWithTag not finding all my objects 0 Answers

How to have a trigger activate animation on another game object. 2 Answers

Code generated animation clip missing component when assigned to an animation controller. 1 Answer

Why my script don't work , Don't have any bug report 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