• 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 Simpowitch · Sep 20, 2019 at 11:56 AM · physicsvector3mathbullettrajectory

Calculating 3D Physics Prediction of Shot Direction with Moving target and moving gun (inertia)

Hi. I need to predict the target position of a moving object in a 3d world for a gun to fire from a distance and hit the moving object.

So far it works perfect when the player is not moving. However when the player starts moving things become tricky. The bullets speed is not constant. It depends on the player's vector3 in comparison to the bullets trajectory. For instance shooting straight forward adds the player's speed to the bulletspeed and vice versa.

My calculation is currently dependent on a constant bullet-speed, which is problematic since the player's ship affects the bullets speed. If anyone has any tips I would be very happy! (google has helped me so far, but with the "inertia" problem (shipspeed+= bulletspeed), I'm lost).

This is my code so far:

 private Vector3 GetDirectionToShoot(Vector3 targetPos, Vector3 targetVelocity)
         {
             Vector3 totarget = targetPos - Ship.Position;
 
             targetVelocity -= Ship.LinearVelocity;
 
             float bulletSpeed = Ship.GunInfo.ProjectileSpeed;
             //bulletSpeed -= Vector3.Distance(Ship.LinearVelocity, targetVelocity);
 
 
             float a = Vector3.Dot(targetVelocity, targetVelocity) - (bulletSpeed * bulletSpeed);
             float b = 2 * Vector3.Dot(targetVelocity, totarget);
             float c = Vector3.Dot(totarget, totarget);
 
             float p = -b / (2 * a);
             float q = (float)Math.Sqrt((b * b) - 4 * a * c) / (2 * a);
 
             float t1 = p - q;
             float t2 = p + q;
             float t;
 
             if (t1 > t2 && t2 > 0)
             {
                 t = t2;
             }
             else
             {
                 t = t1;
             }
 
             Vector3 aimSpot = targetPos + targetVelocity * t;
             Vector3 bulletPath = aimSpot - Ship.Position;
             float timeToImpact = bulletPath.Length() / bulletSpeed;//speed must be in units per second
 
             return aimSpot;
         }

EDIT Made a new easier formula, that should work mathematically with my limited knowledge. But seems to be malfunctioning as well. The new method was like this:

  private Vector3 GetDirectionToShoot(WorldObject target)
         {        
             Vector3 aimSpot = (target.Position - Ship.Position) * Ship.GunInfo.ProjectileSpeed + 
             target.LinearVelocity - Ship.LinearVelocity;
             return aimSpot;
         }
Comment
Add comment · Show 21
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 elenzil · Sep 20, 2019 at 06:12 PM 0
Share

i'm likely mis-understanding, but it sounds like you have some code which calculates the bullet trajectory for a moving target if the player is standing still, and need to modify it to account for the player moving ? if that's the case i think you would just subtract the player velocity from the target velocity before doing your calculation.

avatar image Captain_Pineapple elenzil · Sep 20, 2019 at 07:24 PM 0
Share

Na that wont work since the bullets velocity also get changed by the players velocity. it would work if the bullet velocity was always the same.

avatar image elenzil Captain_Pineapple · Sep 20, 2019 at 08:08 PM 0
Share

well right.

assu$$anonymous$$g you have something like

 vec3 calcBulletInitialVelocityForStationaryPlayer(vec3 playerPos, vec3 targetPos, vec3 targetVel) {...}

then you could write

 vec3 calcBulletInitialVelocityFor$$anonymous$$ovingPlayer(vec3 playerPos, vec3 playerVel, vec3 targetPos, vec3 targetVel) {
   return calcBulletInitialVelocityForStationaryPlayer(playerPos, targetPos, targetVel - playerVel) + playerVel;
 }
avatar image Simpowitch elenzil · Sep 20, 2019 at 08:14 PM 0
Share

Line 5 already has the playerspeed compensation. (the player)

avatar image Simpowitch Simpowitch · Sep 20, 2019 at 08:20 PM 0
Share

Tried a new one as well. But this one seems to not work either. Thought I got rid of the problem with the bullet-speed.

 private Vector3 GetDirectionToShoot(WorldObject target)
         {
          
             Vector3 aimSpot = (target.Position - Ship.Position) * Ship.GunInfo.ProjectileSpeed + target.LinearVelocity - Ship.LinearVelocity;
             return aimSpot;
 }

avatar image Simpowitch Captain_Pineapple · Sep 20, 2019 at 08:15 PM 0
Share

Problem is though that the rest of the calculation is dependent on a set speed, but the speed is set by the direction fired. And the direction fired seems to be dependent on the speed of the bullet.

avatar image elenzil Simpowitch · Sep 20, 2019 at 08:25 PM 1
Share

try adding shipvelocity back in to your calculation of aimspot.

 Vector3 aimSpot = targetPos + (targetVelocity +  Ship.LinearVelocity) * t;
avatar image Simpowitch elenzil · Sep 20, 2019 at 08:38 PM 0
Share

As an addition at the end you mean?

Did you see my other simplyfied version of the formula?

avatar image elenzil Simpowitch · Sep 20, 2019 at 08:40 PM 0
Share

like replace line 31 in your original code w/ that.

avatar image Simpowitch elenzil · Sep 20, 2019 at 08:42 PM 0
Share

did not quite hit the mark i'm afraid "/ thank you though!

Show more comments
avatar image Bunny83 Captain_Pineapple · Sep 20, 2019 at 08:50 PM 0
Share

Uhm, sure that does work. Subtracting the players velocity from the target velocity essentially results in expressing the targets movement relative to the player. So it's like the player doesn't move at all and the target moves at the "new" target speed. That means we can simply consider the bullet speed to always be the same as we do all calculations within the local space of the player. That's relativity at work.


Just think about a bomber dropping a bomb. From the bombers view the bomb just falls down straight while in reality it wil describe a curve.


I haven't checked if the original code actually works, but it seems he already does this in line 5:

 targetVelocity -= Ship.LinearVelocity;

So, considering the code is actually right and does work with a stationary player, it should work with a moving player as well. Of course bulletSpeed in that calculation needs to be the unaltered bullet speed. So simply the speed that the bullet is fired at within the players ship's reference space. In other words the bullet would move at bulletspeed from the player's perspective while relative to the world it would move at bullet speed+player speed.


So there are essentially two possible issues:

  • Either the code doesn't work in general, no matter the player moves or not

  • Or the absolute bulletspeed (worldspace) is actually wrong. It should be set to playerspeed + aimDirection*bulletspeed

elenzil's last comment seems to have spotted be the main issue. While we need to calculate the relative target velocity to calcualte the interception time properly, when you want to calculate the absolute aim position in worldspace we need to use the actual target speed, not the relative one.

avatar image Simpowitch Bunny83 · Sep 20, 2019 at 09:41 PM 0
Share

Yes. The problem is probably related to the bulletspeed. Problem is that it is a float since it's direction isn't known until fired.

Have you seen my new solution, under the edit. Cleaner code and mathematically easier to follow. Still does not work, but should be closer than this heap of a mess i created.

avatar image Bunny83 Simpowitch · Sep 20, 2019 at 10:16 PM 0
Share

Your edit doesn't seem to make much sense. You subtract two positions from each other which give you a relative direction vector. However you named your result aimSpot which seems that it should represent a position like in your first solution. So it's not really clear what you actually expect as result of that method. The name of the method would suggest a direction.


"target.Position - Ship.Position" calculates a direction vector. The magnitude of that vector is the distance between you and your target. $$anonymous$$ultiplying this vector by your projectile speed doesn't make any sense. Dividing would give you the time it takes for the projectile to travel that distance. Finally you add the relative velocity between you and your target to the result. Have you ever thought about the units involved and what you actually calculate? ^^


If your bulletspeed is relatively high (at least 3x the target speed) you can get a rough approximation by calculating the time it takes the bullet to travel from your position to the current target position. Since you now have a rough time you can calculate how much the target will move in that time. However since the movement of the target will change the distance again the time might change as well. So a simple solution is to just do several iterations of that simple calculation to get closer to the actual value you're looking for. Note that this approach will never give you the exact point you have to aim at, but after 2 or 3 iterations the position is usually close enough. However if the bulletspeed is relatively slow (about the same magnitude as your or the enemy movement speed) this approach can fail quickly depending on the relative angles.


However the code on the wiki is actually tested and works properly:

Show more comments
avatar image elenzil Bunny83 · Sep 20, 2019 at 10:59 PM 0
Share

to add to the confusion, here's an old demo of the basic of the situation, but with a stationary player. this is just the math to calculate the projectile velocity to hit a target moving w/ constant velocity. the math should be the same as the wiki code Bunny shared, altho i don't handle the singularity at equal velocities mentioned there. math: https://github.com/elenzil/oxeUnityUtils/blob/master/oxeUtil/Scripts/$$anonymous$$ath/oxeProjectile$$anonymous$$ath.cs demo: https://elenzil.github.io/oxeUnityUtilsExamples/

avatar image Simpowitch elenzil · Sep 20, 2019 at 11:10 PM 0
Share

I'm starting to question the game engine that I'm using. Even this wiki you provide for me yields the same half-working result. Works like a charm when stationary, but when the ship (player) is moving. The shots sill misses. When ship is stationary it perfectly hits any object, moving or not.

Show more comments

1 Reply

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

Answer by Simpowitch · Sep 20, 2019 at 11:54 PM

http://answers.unity.com/comments/1666745/view.html

However the code on the wiki is actually tested and works properly: http://wiki.unity3d.com/index.php/Calculating_Lead_For_Projectiles?_ga=2.83628886.131956639.1568980243-1605833034.1542013817#Calculating_the_intercept_point


From Bunny83.

Note. For me to make this work I had to subtract the currentPosition of the ship/player from the recived Vector3 from the method on this website. To further improve my targeting I searched for targets more towards the front of the ship/player, since shooting backwards is dependent on your bullet speed vs. player speed, which in my case often resulted in a miss since my ship speed was close to the same as the bullet speed.

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

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

bullet doesn't go anywhere 1 Answer

Calculate force applied to rigidbody to make it land at specific location 2 Answers

realistic bullet trajectory 1 Answer

Optimising projectile continuously calculated impact point 2 Answers

Drawing projectile trajectory 5 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