简体   繁体   中英

2D Vector based Ai movement

Im doing turned based movement and I want the enemy Ai will move towards the player if the raycast is hit. I have the raycast down but Im having trouble with the movement. What I first do is determine what quadrant the Ai is in relative to the player being the origin then I want to determine, from the line draw between the player and the enemy, if what the x and y components.

    GameObject player_tran = GameObject.Find ("player");
    if (transform.position.x > player_tran.transform.position.x && transform.position.y < player_tran.transform.position.y) {
        //4th quad if (x is bigger than y) move (left) else move (up)


    } 

    if (transform.position.x < player_tran.transform.position.x && transform.position.y < player_tran.transform.position.y) {
        //3rd quad if (x is bigger than y) move (right) else move (up) 

    } 

    if (transform.position.x < player_tran.transform.position.x && transform.position.y > player_tran.transform.position.y) {
        //2nd quad if (x is bigger than y) move (right) else move (down) 

    } 
    if (transform.position.x > player_tran.transform.position.x && transform.position.y > player_tran.transform.position.y) {
        //1st quad if (x is bigger than y) move (left) else move (down) 

    } 
    else {
    //if they are both equal random moement
    }

`

for example if in the 1st quad and the x component is bigger I want the enemy to move left otherwize down.

edit: what I was trying to do here is create a right triangle where the distance between the enemy and the player is the hypotenuse. Then I would compare the x side with the y side and see which is bigger to determine movement.

So you want the ai to make an axis aligned movement toward the player in the (axis aligned) direction that it has the greater absolute displacement from the player (ties go vertically)?

//shorter variables for my own sanity
var dx = player.x - ai.x;
var dy = player.y - ai.y;
if(Math.Abs(dx) > Math.Abs(dy){
    //assume that move is previously declared/initialised
    move.x = amount_to_move * Math.Sign(dx);
    move.y = 0;
}else{
    move.y = amount_to_move * Math.Sign(dy)
    move.x = 0;
}
//implementation of amount to move, and not going too far when already very close, left to the reader.

As the two dimensions are separable in this case you can just do this.

GameObject player_tran = GameObject.Find ("player");
double dx = 0;
double dy = 0;
if (transform.position.x > player_tran.transform.position.x)
    dx = -1;
} else {
    dx = 1;
}

if (transform.position.y > player_tran.transform.position.y) {
    dy = -1;
} else {
    dy = 1;
}
transform.position += new Vector(dx, dy, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM