• 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
4
Question by ROOKIE · Jul 20, 2011 at 02:18 AM · bullet

How to make enemy Cannonball fall on moving target position.

How do I make enemy cannon ball fall on target position?

My target (PLAYER) is moving and I would like the enemy turret (which catapults cannonball in arc) to be always able to hit target position - where it was recently standing when the cannon ball was catapulted.

So that if target would stand still the cannonball would actually land on target.

So far my cannon ball always lands in same distance from turret.

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

1 Reply

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

Answer by aldonaletto · Jul 20, 2011 at 04:29 AM

The easiest way to do that is to shoot always at a 45 degrees elevation, and adjust the velocity to reach the target distance (45 degrees gives the greatest range - read about it in the Temple of Wisdom, aka Wikipedia). If the target and the turret are at the same height, the initial cannon ball velocity is given by **Mathf.Sqrt(distance gravity).
The function
BallisticVel in the script below returns the velocity necessary to hit the object defined by myTarget:*

var myTarget: Transform; var cannonball: GameObject;

function BallisticVel(target: Transform): Vector3 {

 var dir = target.position - transform.position; // get target direction
 var h = dir.y;  // get height difference
 dir.y = 0;  // retain only the horizontal direction
 var dist = dir.magnitude ;  // get horizontal distance
 dir.y = dist;  // set elevation to 45 degrees
 dist += h;  // correct for different heights
 var vel = Mathf.Sqrt(dist * Physics.gravity.magnitude);
 return vel * dir.normalized;  // returns Vector3 velocity

}

function Update(){

 if (Input.GetKeyDown("b")){
     var ball: GameObject = Instantiate(cannonball, transform.position, transform.rotation);
     ball.rigidbody.velocity = BallisticVel(myTarget);
     Destroy(ball, 10);
 }

}

To test this script, assign it to an empty object, drag the target to myTarget and your cannon ball prefab to cannonball, then press the key b to shot.

NOTE: Set the object position to a height that ensures the cannon ball will not touch any collider when instantiated, or this will alter the cannon ball movement and it will never reach the target. If you want to place the game object in your turret, set Is Trigger in the turret's collider to avoid this interference.

EDITED: I modified the script a little to compensate for small differences in height between the turret and the target. The idea is: the cannon ball reaches the destination point at the same angle it was launched; since we are shooting at 45 degrees, any difference in height will produce a similar difference in the distance - at least near to the calculated impact point. In practical terms, if the target is 5 units above the turret, I can shoot to a point 5 units farther, and the cannon ball trajectory will pass through the actual player position. It's a valid approximation for height differences about up to 20% of the horizontal distance, but the error may become excessive outside this range. There's a complete equation in the reference I provided, but it seems impossible to solve with linear methods, so this approximation may be the best alternative.

Comment
Add comment · Show 10 · 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 tieTYT · Aug 17, 2011 at 07:18 PM 0
Share

I'm super new to this so this is why I'm asking. Shouldn't you put your logic inside of FixedUpdate() ins$$anonymous$$d of Update()? If not, can you explain why?

avatar image Rafes · Aug 17, 2011 at 07:39 PM 1
Share

I could be wrong but it looks like he is setting something once (a constant velocity). FixedUpdate should only be necessary if working with physics as a true update (every frame). In a real implementation you wouldn't want to use Update at all since it would run everyframe but only be needed on the more rare occasion "b" is pressed. You'd want some sort of input manager to send out events. If it is only one object its perfectly O$$anonymous$$ though. $$anonymous$$y point is, this isn't being used to actually update anything.

avatar image aldonaletto · Aug 17, 2011 at 08:23 PM 1
Share

@Rafes is right: the rigidbody velocity is set only when you shoot, so it makes no difference where it is done - the new velocity will take effect only in the next physics cycle (which is in sync with FixedUpdate). You must use FixedUpdate to make regular changes - to move with Translate or to apply some constant or regularly variable force, for instance.

avatar image tieTYT · Aug 18, 2011 at 07:47 AM 0
Share

O$$anonymous$$, I implemented this and it seems almost perfect. But, I notice that as I get closer to the source of projectile, it lands short of its target. It also seems like it gives me NaN return values if I get pretty close (but not on top of) my source. Any idea why that's happening? I set the drag on my ball to 0.

avatar image aldonaletto · Aug 18, 2011 at 11:57 AM 1
Share

Try to position the turret at the same height as the player. The function BallisticVel assumes that the turret (spawn point) and the target are at the same height (same Y), but can correct for "small" differences (something like up to 20% of the horizontal distance).
If the heights are different, a trajectory error will gradually appear as the target gets closer to the turret. If the target is lower than the turret, this error will produce NANs when the horizontal distance becomes lower than the height difference.

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

8 People are following this question.

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

Related Questions

Bullet movement from guns rotation 1 Answer

Help with turn based bullet fire 0 Answers

Shooting a bullet in Unity 1 Answer

Need Help with Health Script 0 Answers

Bullets. Rotation Probelm 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