• 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
Question by coolbird22 · Oct 25, 2014 at 04:50 PM · instantiateprojectilethrowgrenade

How to angle projectiles depending on where the mouse is clicked ?

Consider the projectile to be something like a grenade with a parabolic trajectory. Wherever on the horizontal axis that the mouse click happens, the projectile is supposed to be thrown in that angle, and the vertical axis decides the height of the trajectory. The camera angle is locked.

Also, how to make the projectile rotate in the direction of the trajectory ?

Code I'm using to throw the projectile is as below:

     public GameObject grenade;
     public float throwPower = 100;
 
     void  Update (){
         if (Input.GetButtonDown("Fire1")) {
             GameObject clone; 
             clone = Instantiate(grenade, transform.position, transform.rotation); 
             clone.rigidbody.velocity = transform.TransformDirection(Vector3.for­ward * throwPower); 
         }
     }

though I get an error Unexpected symbol for', expecting identifier' for the line

 clone.rigidbody.velocity = transform.TransformDirection(Vector3.for­ward * throwPower);

The below is an example of various directions the projectile can be thrown in depending on where the mouse click happens.

alt text

touchscreen.png (108.4 kB)
Comment

People who like this

0 Show 3
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 AlwaysSunny · Oct 25, 2014 at 05:25 PM 0
Share

Seems like the "easy" way would be having a transform on your shooter object which tries to look at the mouse position in world space. Perhaps at a distant point on the camera's view plane, for instance? Projectiles get launched from that transform's position, and get an impulse in the direction of the transform's "forward". This way gives you some extra play over where the projectile spawns from. If it's launching from the camera's center, you could just as easily use that "camera ray" informed by the mouse as the projectile's initial velocity.

avatar image coolbird22 · Oct 25, 2014 at 06:57 PM 0
Share

I didn't quite understand what you meant by that. What I basically need to do is somehow create a vector that starts from the middle of the screen and ends where the mouse click happens, and make the projectile continue in that vectors' direction and also rotate that way.

avatar image AlwaysSunny · Oct 26, 2014 at 12:46 AM 0
Share

How about a ScreenPointToRay based on the mouse position:
http://docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

1 Reply

· Add your reply
  • Sort: 
avatar image

Answer by jabez · Oct 26, 2014 at 01:42 AM

Hello there C:, i would do a raycast then minus the hit point with your position to get the direction i will post a script as an example. Vector3 Dir = (hit.point - transform.position) may have to be Vector3 Dir = transform.position - hit.point) anyways enjoy!

     void Update () {
                 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                 RaycastHit hit;
                 if (Physics.Raycast(ray, out hit, 100))
                     Debug.DrawLine(ray.origin, hit.point);
             Vector3 Dir = (hit.point - transform.position);
             transform.rigidbody.AddForce (Dir * 4);
         }
Comment

People who like this

0 Show 7 · 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 AlwaysSunny · Oct 26, 2014 at 02:12 AM 0
Share

My impression was that the original poster didn't necessarily want the point where a mouse ray intersects with the world geometry. If I'm mistaken, this answer is suitable.

avatar image coolbird22 · Oct 26, 2014 at 06:12 AM 0
Share

@AlwaysSunny - Ah, sorry if I wasn't clear in what I needed. @jabez - I used your code and added some stuff to it. The projectile fires everytime a click happens, but it doesn't do so in the direction of the mouse click. It fires only in the straight direction with the same height. Here is the code as it stands currently.

 public GameObject grenade;
     public float throwPower = 100;
 
     void Update () {
         if (Input.GetMouseButtonDown(0)){
             Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
             RaycastHit hit;
             if (Physics.Raycast(ray, out hit, 100))
                 Debug.DrawLine(ray.origin, hit.point, Color.yellow);
             Vector3 Dir = (hit.point - transform.position);
 
             GameObject clone; 
             clone = Instantiate(grenade, transform.position, transform.rotation) as GameObject; 
             clone.transform.rigidbody.AddForce (Dir * throwPower);
         }
     }
avatar image AlwaysSunny · Oct 26, 2014 at 06:50 AM 0
Share

Right, right, so the part about parabolic trajectory is where you're stuck, am I correct?

Wanting a rigidbody to be "tossed at a target" rather than "shot in a direction" requires some physics math. Calculating a trajectory is one thing, but what you want is the initial velocity which creates a trajectory which satisfies your start / end point constraints. The problem is, there are an infinite number of initial velocities which might satisfy your requirement. How you will ultimately choose from among them the one that best matches your intention is... confusing. I guess if you limit the scalar of the initial velocity to a fixed magnitude, that could give you a single desired initial velocity vector.

Here are your four basic kinematic equations, one or more of which you'll need to make use of as you solve for your unknown (the initial velocity): http://www.physicsclassroom.com/class/1DKin/Lesson-6/Kinematic-Equations

If this is just totally daunting and not what you had in mind, consider whether you absolutely need to pre-determine where your tossed-projectile will land.

EDIT: Okay, I re-read your original question, and now see that you also want the height of the trajectory to be controlled. Sorry for missing that. Unfortunately, this further complicates an already complicated issue. I don't recall whether I've ever solved this particular kind of problem before - doesn't using vertical mouse position to inform the trajectory apex invalidate the whole concept of also using mouse position to pre-determine the end point?

avatar image coolbird22 · Oct 26, 2014 at 07:20 AM 0
Share

All of the parabolic trajectory is being taken care of by Unitys' physics engine. I'm just not able to get it to fire in the direction where the mouse is clicking. It is firing only in the straight direction, perpendicular to the camera.

avatar image coolbird22 · Oct 26, 2014 at 01:18 PM 0
Share

Ok, turning on the Box Collider of the object to which the ray was colliding, made the angle of the projectile work. So, now I can click anywhere on the screen and the projectile goes in that direction, along with the elevation as required. Need to get the rotation to work now.

Update: I got the rotation to work somewhat, but it doesn't rotate in the direction of the throw. Here is what I added at the end of the code

 clone.transform.rigidbody.AddTorque (Vector3.right * rpm);

Show more comments

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

29 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

Related Questions

one gameobject instantiaton not 100 3 Answers

IEnumerator not looping correctly? 1 Answer

Checking if object intersects? 1 Answer

Creating more objects with code. 2 Answers

Rigidbody projectile jittering 0 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