Search Unity

Question 2d Enemy follow AI with rigidbody

Discussion in 'Scripting' started by SpyderManToo, Feb 19, 2021.

  1. SpyderManToo

    SpyderManToo

    Joined:
    Dec 8, 2020
    Posts:
    387
    How do i make a 2d enemy follow me using rigidbody and not vector2.movetowards?

    ive tried movetowards but it doesn't work bc collisions are kinda weird.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    You could try putting a CharacterController on the enemy instead of a Rigidbody and move with CharacterController.Move. That will handle collisions nicely.
     
  3. SpyderManToo

    SpyderManToo

    Joined:
    Dec 8, 2020
    Posts:
    387
    is there a way i could do it through script because i dont like having some things move with scirpt and others with components
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    All Scripts are components.
    Most Components are scripts.

    You can only move the CharacterController controller from a script using CharacterController.Move()
     
  5. SpyderManToo

    SpyderManToo

    Joined:
    Dec 8, 2020
    Posts:
    387
    ok yea yea maybe i worded that wrong.
    does the character controller work in 2d?
    is there a way i can recreate hwo it works in script? because i dont really want to use the charactercontroller if i dont have to
     
  6. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Oh - no it doesn't work in 2D. To recreate it you would basically do the following each frame:
    • Decide what direction and how far you want to move (in a Vector3 variable)
    • Do some kind of raycast from your character in that direction (Or BoxCast or CircleCast, whichever matches your character's shape the best)
    • if you don't hit anything, go ahead and move.
    • If you do hit something, figure out how far away the object is (the raycast hit distance will tell you) and only move that far instead so you don't go through the object.
     
  7. SpyderManToo

    SpyderManToo

    Joined:
    Dec 8, 2020
    Posts:
    387
    how do i do that exactly? im not that skilled in scripting
     
  8. SpyderManToo

    SpyderManToo

    Joined:
    Dec 8, 2020
    Posts:
    387