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 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!
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:
Here is what I got for my top-down game with no gravity after reading it, maybe it’ll help some people passing by: