Home > OS >  Enemy bot moves away from the player Unity3D
Enemy bot moves away from the player Unity3D

Time:05-18

I'm making top down shooting game. I wrote the code where enemies spawn randomly on map and they're trying to catch you. I made them do that and also I wrote a code to make them look at you. Basically rotate towards you only on Z axis. But problem is that when they are spawned on players' right, enemy is moving away from player. but if I rotate and start to move they are trying to fix themselves. Here's my script:

void FixedUpdate () {
        Vector3 difference = player.position - transform.position;
        float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
        Vector2 toTarget = player.transform.position - transform.position;
        float speed = 1.5f;
         
        transform.Translate(toTarget * speed * Time.deltaTime);
    }

CodePudding user response:

Consider that Translate is a relative modifier. For this reason, when you specify the direction in the Translate itself, the movement becomes confused. Use Vector3.MoveTowards to solve the problem. If your game is 2D, you can also use Vector2 like below:

Vector2.MoveTowards(currentPosition, targetPosition, step);

Preferably you can fix this code like this and set the return value of MoveTowards equal to transform.Position.

void FixedUpdate () {
    Vector3 difference = player.position - transform.position;
    float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
    float speed = 1.5f;
    
    // replace Translate to MoveTowards
    transform.position = Vector3.MoveTowards(transform.position, player.position, Time.deltaTime * speed);
}
  • Related