- Home /
Question by
yknr371 · Oct 01, 2017 at 01:31 AM ·
ai2d-gameplaydegrees
(2D) Why does my Opponent AI think the Player is ahead of them when it is actually Behind?
I am working on a single-player 2d dogfighting game, and am running into issues with to AI. When the player is right on the AI's tail, the AI's code says that the player is right in front of them. As you can imagine this is difficult to google, so, here I am. Any help would be greatly appreciated.
CODE (issue and related parts):
public enum job
{
kill,follow,patrol,dock,travel
};
public bool moveForward = false;
public bool turnRight = false;
public bool turnLeft = false;
public Transform target;
public job currentJob;
void Update() {
executeJob();
}
void executeJob()
{
if (currentJob == job.kill)
{
kill();
}
else if (currentJob == job.follow)
{
follow();
}
else if (currentJob == job.patrol)
{
patrol();
}
else if (currentJob == job.dock)
{
dock();
}
else if (currentJob == job.travel)
{
travel();
}
}
void follow()
{
if (get_TargetDistance() > 20)
{
basicMove();
}
}
float get_SelfDegrees()
{
return transform.rotation.eulerAngles.z;
}
float get_TargetDegrees()
{ //gets slope of line connecting self and target and converts it to degrees
return Mathf.Atan(
(target.position.y - transform.position.y) / (target.position.x - transform.position.x)
) *Mathf.Rad2Deg;
}
float fix_OutOfRangeDegrees(float degreeDifference)
{
while (true)
{
if (degreeDifference < 0)
{
degreeDifference += 360;
}
else if(degreeDifference > 360)
{
degreeDifference -= 360;
}else
{
break;
}
}
return degreeDifference;
}
void basicMove()
{
float degreeDifference = 180;
if (get_TargetDegrees() + get_SelfDegrees() != 0)
{ //treats behind as if it is ahead
degreeDifference = get_TargetDegrees() - get_SelfDegrees();
degreeDifference = fix_OutOfRangeDegrees(degreeDifference);
}
Debug.Log(degreeDifference);
if (degreeDifference <= 180)
{
turnLeft = true;
turnRight = false;
}
if (degreeDifference >180)
{
turnRight = true;
turnLeft = false;
}
if ((330 <= degreeDifference && degreeDifference <= 360)
|| (0 <= degreeDifference && degreeDifference <= 30))
{
moveForward = true;
}
else
{
moveForward = false;
}
}
Comment
Your answer
Follow this Question
Related Questions
Unity 2D vs Unity 3D 0 Answers
AI is over floor When player jump 1 Answer
How would I confine an object to the ground? 2 Answers
AI help people 1 Answer
Send an enemy back to its spawn point using waypoints 2 Answers