Search Unity

Animating NPCs

Discussion in '2D' started by bnd10706_unity, Sep 11, 2019.

  1. bnd10706_unity

    bnd10706_unity

    Joined:
    Aug 8, 2019
    Posts:
    4
    So I have a an NPC set up with an AI to wonder.

    I cannot figure out how to animate it.

    I have a player controller for my player but, its based on keyboard inputs to animate the player, there is no keyboard input for the wondering character.

    I am having a hard time animating it.
     
  2. Pixitales

    Pixitales

    Joined:
    Oct 24, 2018
    Posts:
    227
    i don't think it going to work out the way you wanted like that. I made a character script which contains my animate movement. Then my enemy, npc and player script inherits from it so they all share the same animate movement code. My movement input in the player script and input manager script. Check out unity Inscope rpg tutorial. It helped me a lot.
     
    Last edited: Sep 17, 2019
  3. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    833
    You will need your NPC to have a rigidbody component. Design Methods for the directions:
    Code (CSharp):
    1. private Rigidbody2D npc; // If the script is on you NPC this will be okay
    2. //If not, consider serializing the field or making it public.
    3. private bool canMove;
    4.  
    5. private void Start()
    6. {
    7. npc = GetComponent<Rigidbody2D>();
    8. canMove = true;
    9. }
    10.  
    11. private void Update()
    12. {
    13. // You will call your functions here.
    14. // However, you want to define your conditions of movement
    15. // in perhaps an IENumerator or use ray casting.
    16.  
    17. // if your raycast detects a wall, make your enemy change direction
    18.  
    19. // otherwise, if your NPC is freeroam you can use an IENumerator
    20. // to let it move for a certain amount of time then change direction.
    21.  
    22. if(canMove == true)
    23. {
    24. StartCoroutine(NPCMovement());
    25. }
    26.  
    27. }
    28.  
    29. void MoveLeft()
    30. {
    31. npc.velocity = Vector2.left;
    32. //Include you animation and other relevant sequences here
    33. }
    34.  
    35. void MoveRight()
    36. {
    37. npc.velocity = Vector2.right;
    38. //Include you animation and other relevant sequences here
    39. }
    40.  
    A demonstration of IENumerator:

    Code (CSharp):
    1. IENumerator NPCMovement()
    2. {
    3. canMove=false;
    4. MoveLeft();
    5. yield return new WaitForSeconds(5f);
    6. MoveRight();
    7. yield return new WaitForSeconds(5f);
    8. canMove=true;
    9. }
     
    Last edited: Sep 17, 2019