Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 /
avatar image
0
Question by cow_co · May 01, 2015 at 05:09 PM · 2drotationai

2D AI: How to get the AI to aim ahead of its target?

So I am making a 2D space combat game, with everything free to move in the x-y plane. I want my enemies to be able to aim ahead of the player, so they can shoot accurately. However,I am having trouble doing this. The relevant code in the game is

                 Vector3 predictedPos = new Vector3();
                 predictedPos = (Vector3)targetRigid.velocity * Time.fixedDeltaTime + targetTransform.position;
 
                 Vector3 pursuitDir = new Vector3();
                 pursuitDir = predictedPos - gameObject.transform.position;    //pursuit direction, predicting where the target will be.
 
                 transform.LookAt(predictedPos * leadAmount);
                 transform.Rotate(new Vector3(0, 90, 0), Space.Self);    //corrects the issue with the rotation.

This provides an alright response, but the AI doesn't lead its target enough, so it is always lagging its shots behind the player. It doesn't rotate quickly enough. Unfortunately I don't think there's a way to change the rotation speed used in transform.LookAt, is there?

So how do I deal with this?

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

3 Replies

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

Answer by Scribe · May 01, 2015 at 05:19 PM

So this is a rough guess at how to do it, I think you have forgotten to take into account the speed of the bullet, unless I am mistaken, and the 'bullet' always takes 1 frame to reach its target?

 float bulletSpeed; //units per second
 
 Vector3 PredictPosition(Rigidbody2D targetRigid){
     Vector3 pos = targetRigid.position;
     Vector3 dir = targetRigid.velocity;
     
     float dist = (pos-transform.position).magnitude;
     
     return pos + (dist/bulletSpeed)*dir;
 }


This will still be somewhat incorrect, as in, it's not the best prediction you can get from the information. The best you can would be based on computing the distance at the expected position, however as the expected position is based on the distance, it becomes a little more complicated. It can be done very easily iteratively, and probably also with some simple maths, but I have just got back from a 2 hour algebra lecture, and I can't think about maths right now!

Hope that helps :)

Scribe

Comment
Add comment · Show 6 · 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 Spinnernicholas · May 01, 2015 at 05:52 PM 0
Share

I agree with this.

avatar image Sessional · May 01, 2015 at 05:54 PM 0
Share

This would be an accurate way of doing it. You could also look into using a lerp, but it can get super complicated super fast depending on variables.

avatar image cow_co · May 01, 2015 at 06:10 PM 0
Share

Thanks for the reply, scribe! The main issue I'm having now is the fact that the AI just doesn't turn quickly enough. I have your code giving the predicted point, and I'm using transform.LookAt. However, the AI just doesn'trotate as fast as I'd like. Is there a way to set a game object's angular speed? I should have thought there would be.

avatar image Sessional · May 01, 2015 at 06:16 PM 2
Share

http://docs.unity3d.com/ScriptReference/Rigidbody2D-angularVelocity.html There is in the rigidbody stuff. If you aren't using a rigidbody it should move instantly?

avatar image cow_co · May 01, 2015 at 06:22 PM 0
Share

yeah, I'm using a rigidbody. This is perfect, thanks!

Thanks also to Scribe again for the answer!

Show more comments
avatar image
1

Answer by ShaidarJB · Apr 27, 2016 at 05:20 AM

A relatively simple way of performing a prediction that I've found was by using:

 Vector3 PredictPosition(GameObject target){
         Vector3 velocity = target.GetComponent<Rigidbody2D>().velocity;
         float time = Vector3.Distance(transform.position,target.transform.position)/(bulletSpeed * Time.smoothDeltaTime);
         Vector3    coef = velocity*time;
         Vector3 newTarget = target.transform.position + coef;
         return newTarget;
     }
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
1

Answer by ArcticPinou · Aug 26, 2020 at 06:05 PM

Hi, I know I'm replying to a 4 year old post but since it's first when I search for AI aiming in Unity, I think it's worth some precision. This article explains the maths behind the exact prediction incredibly well: https://www.gamasutra.com/blogs/KainShin/20090515/83954/Predictive_Aim_Mathematics_for_AI_Targeting.php

Here is what I got for my top-down game with no gravity after reading it, maybe it'll help some people passing by:

 public static Vector3 PredictAim(Vector3 shootPos, Vector3 targetPos, Vector3 targetVel, float projSpeed)
 {
     if (targetVel.sqrMagnitude <= 0f)
     {
         return targetPos;
     }
     else
     {
         Vector3 targetToBullet = shootPos - targetPos;
         float distToTargetSqr = (shootPos - targetPos).sqrMagnitude;
         float distToTarget = (shootPos - targetPos).magnitude;
         Vector3 targetToBulletNorm = targetToBullet / distToTarget;
         float tarSpeed = targetVel.magnitude;
         float tarSpeedSqr = targetVel.sqrMagnitude;
         Vector3 tarVelNorm = targetVel / tarSpeed;
         float projSpeedSqr = projSpeed * projSpeed;
         float cosTheta = Vector3.Dot(targetToBulletNorm, tarVelNorm);
         
         float offsetSqrPart = 2 * distToTarget * tarSpeed * cosTheta;
         offsetSqrPart *= offsetSqrPart;
         float offset = Mathf.Sqrt(firstEqPart + 4 * (projSpeedSqr - tarSpeedSqr) * distToTargetSqr);
 
         float estimatedTravelTime = (-2 * distToTarget * tarSpeed * cosTheta + offset) / (2 * (projSpeedSqr - tarSpeedSqr));
 
 
         if (estimatedTravelTime < 0 || estimatedTravelTime == float.NaN)
         {
             return targetPos;
         }
         else
         {
             return targetPos + tarVelNorm * tarSpeed * estimatedTravelTime;
         }
     }
 }
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.

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

Look at and animal ai 0 Answers

Pysics not working as expected 1 Answer

My Enemy's Graphics always rotate towards me even when the CharacterController does not 0 Answers

Joystick move Left Right and down, plus rotation. 0 Answers

Transform Z axis rotation from center of screen toward mouse cursor with Quaternion.LookRotation for a top down game. 2 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