Search Unity

Question Enemy GameObject standing still while the player moves

Discussion in 'Physics' started by Sandtile, Sep 25, 2020.

  1. Sandtile

    Sandtile

    Joined:
    Dec 9, 2018
    Posts:
    3
    Hello, I'm new to Unity(joined in 2018 but started learning on this August/September), and I'm having some problems with an enemy following player script.
    While I'm moving the player or while it is jumping, the enemy stands still or moves as least smoothly as possible, but when I keep the player standing still, the enemy starts moving again towards his position(this also has some smoothing problems). As a beginner, I have no idea why is this happening, and even trying to solve this "myself" for hours straight and googling this problem multiple times with different words, I can't find anything similar.

    The code for the enemy movement is:


    Code (CSharp):
    1. Rigidbody rb;
    2. public Transform player;
    3. Vector3 ppos;
    4. Vector3 distancetoplayer;
    5. float movespeed = 15f;
    6.  
    7.  
    8. void Start(){
    9. rb = GetComponent<Rigidbody>();
    10. }
    11.  
    12.  
    13. void Update()
    14.     {
    15.         //ENEMY LOOKS AT PLAYER!
    16.         ppos = new Vector3(player.position.x, gameObject.transform.position.y, player.position.z);
    17.         gameObject.transform.LookAt(ppos);
    18.    
    19.  
    20.         //ENEMY FOLLOWS THE PLAYER!
    21.         distancetoplayer = transform.position - player.position;
    22.         distancetoplayer.Normalize();
    23.         rb.MovePosition(transform.position - distancetoplayer * movespeed * Time.deltaTime);
    24.  
    25.  
    26.     }
    The code above is actually part of a script where there's also the enemy health code, but it is separated in another function, so it doesn't affect the code.

    • Also, how do I guarantee that the enemy won't follow the player through the y axis?

    EDIT:
    I kind of found a solution, but it's confusing. For some reason, if the enemy's RigidBody is marked as kinematic, it stops while the player is moving. Else, it all works fine... why?

    Thanks for reading. ;)
     
    Last edited: Sep 27, 2020