• 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 Amicus1 · May 10, 2017 at 07:16 PM · 2dprojectilecannon

Setting the velocity of a projectile based on the angle of the cannon

Hello, I am trying to make a top-down 2d game, and it involves a cannon that shoots food particles, which are then supposed to bounce around the arena. I made the cannon instantiate the food particle, and I made a food object which will collide with my boundaries. However, I am stuck on setting the particle's velocity so that it continues in the direction the cannon is pointing. (The cannon rotates back and forth, so it is not the same vector all the time.) If I set the velocity to a constant vector and change the rotation, will it go in the direction of the rotation? or are the vectors relative to world space? Do I have to do trig in order to calculate the x and y values for the vector? I thought of doing a raycast, and making the food particle look at the endpoint of the raycast. Would that work? Thanks anybody who answers.

Comment
Add comment · Show 18
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 TreyH · May 10, 2017 at 07:31 PM 0
Share

You could do the trig, or you could just AddForce in the direction your cannon is facing.

avatar image RobAnthem · May 10, 2017 at 07:36 PM 0
Share

Well you would simply do something like this.

 myBullet.transform.forward = cannon.transform.forward;

Then move it based on its forward position.

 myBullet.rb.velocity = myBullet.transform.forward * bulletSpeed * Time.fixedDeltaTime;


avatar image Amicus1 · May 10, 2017 at 08:03 PM 0
Share

So you're saying that as the cannon turns, its vector turns with it? Also, I don't see why I need a deltaTime.

avatar image RobAnthem Amicus1 · May 10, 2017 at 08:07 PM 0
Share

No I mean on instantiation of the bullet, the bullet should be set to inherit the cannons facing direction.

Also, when moving an object with physics, you should always use deltaTime because frames are always inconsistent, deltaTime is the only accurate way to get consistent movement.

avatar image Amicus1 · May 10, 2017 at 08:21 PM 0
Share

So I copied your first piece of code into my cannon script underneath the "instantiate the food particle" line, and I copied the second one into the food script in the update function. However, ins$$anonymous$$d of starting the particle at the cannon and immediately setting its direction to the cannon's current angle, it starts it at the origin and moves it with all the other food particles that get shot, in a clump as the cannon turns. What did I do wrong? Cannon instantiate code:

 void Update () {
         Rotate();
         if ((Random.Range(1, 151) == 1))
         {
             Instantiate(food, cannon.GetComponent<Transform>()); 
             food.transform.forward = cannon.transform.forward;
         }

Food script

 void Update ()
     {
         food.GetComponent<Rigidbody2D>().velocity = food.transform.forward * particleSpeed * Time.fixedDeltaTime;
     }

avatar image RobAnthem Amicus1 · May 10, 2017 at 08:36 PM 0
Share

You're childing the food to the cannon, so its forward direction is no longer relative to world space, ins$$anonymous$$d you are setting the local forward direction of the food to the world forward direction of the cannon.

Also, you should never run a GetComponent in an Update. You should create a projectile class for your food and do something like this.

 public class Projectile : $$anonymous$$onoBehaviour
 {
     public Rigidbody2D body;
     public float speed;
     void Awake()
     {
         if (body == null)
         {
             body = GetComponent<Rigidbody2D>();
         }
     }
     void FixedUpdate()
     {
         body.velocity = transform.forward * speed * Time.fixedDeltaTime;
     }
 }

Then your cannon can have the food prefab and do this.

 public class Cannon : $$anonymous$$onoBehaviour
 {
     public Projectile food;
     public float ForwardOffset;
     public void FireCannon()
     {
         Projectile f = Instantiate(food, transform.position + transform.forward * ForwardOffset, transform.rotation);
         f.transform.forward = transform.forward;
     }
     void Update () {
          Rotate();
          if ((Random.Range(1, 151) == 1))
          {
              FireCannon();
          }
     }
 }

avatar image Amicus1 RobAnthem · May 10, 2017 at 09:59 PM 0
Share

Did that, but it says, "The object you want to instantiate is null". I put the projectile script as another component on the cannon object if it makes any difference.

avatar image RobAnthem Amicus1 · May 10, 2017 at 10:06 PM 0
Share

It needs to be a prefab in your filesystem, drag and drop it from your Scene into your Project area, then from your Project area onto the Food slot of the Cannon.

avatar image Amicus1 RobAnthem · May 10, 2017 at 10:27 PM 0
Share

Well, now I have a cannon that shoots food particles out the back. And then there are always two that get stuck in the corner behind the cannon. How to change the firing direction?

avatar image RobAnthem Amicus1 · May 10, 2017 at 10:42 PM 0
Share

This is usually caused by the models forward position not being the actual forward, I usually solve it by making an empty gameobject the actual object and place the model inside, but you could always just do

 f.transform.forward = -transform.forward;

Unless it is the food that is backwards, in which case.

 body.velocity = -transform.forward * speed * Time.fixedDeltaTime;


avatar image Amicus1 RobAnthem · May 10, 2017 at 10:59 PM 0
Share

Neither of those works.

avatar image RobAnthem Amicus1 · May 12, 2017 at 05:36 PM 0
Share

Well if none of these suggestions worked, then something else is going on and we don't have all the information. Please post your code for both the Cannon and the Food.

avatar image Amicus1 RobAnthem · May 12, 2017 at 05:48 PM 0
Share
 using UnityEngine;
 
 public class CannonScript : $$anonymous$$onoBehaviour {
     public float CWbound;
     public float CCWbound;
     public float angle; 
     public float degPerFrame = 3f;
     public bool isCWdirection; // If true, cannon is moving CW. If false, cannon moving CCW.
     public GameObject cannon;
     public Projectile food;
     public float ForwardOffset;
     public void FireCannon()
     {
         Projectile f = Instantiate(food, transform.position + transform.forward * ForwardOffset, transform.rotation);
         f.transform.forward = -transform.forward;
     }
     // Use this for initialization
     void Start () {
         
     }
     
     // Update is called once per frame
     void Update () {
         Rotate();
         if ((Random.Range(1, 151) == 1))
         {
             FireCannon();
         }
     }
     void Rotate () {
         if (cannon.GetComponent<Rigidbody2D>().rotation<=CWbound)
         {
             isCWdirection = false;//If the cannon has hit the boundary on the clockwise side, start turning CCW
         }
         else if (cannon.GetComponent<Rigidbody2D>().rotation >= CCWbound)
         {
             isCWdirection = true;//If the cannon has hit the boundary on the counterclockwise side, start turning CW
         }
         if (isCWdirection)
         {
             cannon.GetComponent<Rigidbody2D>().$$anonymous$$oveRotation(cannon.GetComponent<Rigidbody2D>().rotation - degPerFrame);
            angle = cannon.GetComponent<Rigidbody2D>().rotation;
         }
         else if (!isCWdirection)
         {
             cannon.GetComponent<Rigidbody2D>().$$anonymous$$oveRotation(cannon.GetComponent<Rigidbody2D>().rotation + degPerFrame);
             angle = cannon.GetComponent<Rigidbody2D>().rotation;
         }
         
     }
 }
Show more comments
avatar image RobAnthem Amicus1 · May 12, 2017 at 05:56 PM 0
Share

velocity must be declared every frame, not on Start(). So it should be more like this.

  public class FoodScript : $$anonymous$$onoBehaviour {
      public GameObject food;
      public Rigidbody2D body;
      public float particleSpeed = 1;
  
      // Use this for initialization
      void Start () {
          if (body == null)
         {
            body = food.GetComponent<Rigidbody2D >();
         }
      }
      
      // FixedUpdate is called once per fixed frame
      void FixedUpdate ()
      {
                   body .velocity = food.transform.forward * particleSpeed * Time.fixedDeltaTime;
      }
  }
avatar image Amicus1 RobAnthem · May 12, 2017 at 06:05 PM 0
Share

They still shot from the back of the cannons, but don't bounce.

avatar image RobAnthem Amicus1 · May 12, 2017 at 06:08 PM 0
Share

then replace

 body .velocity = food.transform.forward * particleSpeed * Time.fixedDeltaTime;

with

 body .velocity = -food.transform.forward * particleSpeed * Time.fixedDeltaTime;

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by ifurkend · May 17, 2017 at 07:30 AM

Check if the simulation space of your cannon particle system main module. If it's "local" then it's the cause of your issue and can be fixed by changing to "world".

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 Amicus1 · May 19, 2017 at 02:01 PM

First, I probably should clarify that the cannon does not actually create a "particle system", the food particles are each separate gameobjects.

Second: I think I have finally figured it out. I have the cannon instantiate the food particle with the same rotation as the cannon had at the time of firing. Then I have in the Start() in the food script, a trig thing that turns the angle of the food particle into a Vector2, and on each update, do a AddForce() along that vector. Now I just have to stop the force once it collides with the wall, so that it can actually bounce around the arena

Thanks everybody again!

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

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

6 People are following this question.

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

Related Questions

How do I get my character to shoot a projectile in the direction of the cursor? 1 Answer

Projectile move towards mouse cursor 3 Answers

2d side scroller projectile/firing weapon script help needed. 1 Answer

simple trajectory for rigidbody 2 Answers

ball breaks through walls 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