Unity simple 2D Enemy AI Follow Tutorial

Поделиться
HTML-код
  • Опубликовано: 21 сен 2024
  • Like and subscribe for more ai video
    Main Channel: / bblakeyyy
    Patreon with fully explained c# scripts:
    / blakeygames
    NEW SERVER LINK: / discord
    Silhouette Dash free download:
    blakey-games.i...
    Join the discord community!:
    / discord
    Play my games! :
    blakey-games.i...
    play.google.co...
    Watch me Live on twitch: / bblakeyyy
    My Website!: bblakeygames.w... Audio used in my videos:
    ♪ Onion (Prod. by Lukrembo)
    Link : • (no copyright music) l...
    ♪ Branch (Prod. by Lukrembo)
    Link : • (no copyright music) c...
    ♪ Biscuit (Prod. by Lukrembo)
    Link : • (no copyright music) l...
    ♪ Bread (Prod. by Lukrembo)
    Link : • (no copyright music) j...

Комментарии • 128

  • @kealandoherty429
    @kealandoherty429 Год назад +32

    I'm using this as an "approaching wall of death" for a university assignment lmao, the tutorial was great and simple thanks a lot!

    • @morebblakeyyy
      @morebblakeyyy  Год назад +4

      Awesome! Good look with your uni assignment my friend

  • @rmt3589
    @rmt3589 Год назад +28

    Gonna use this for enemy ai in an ACTUALLY simple game. Went camping, and had to spend the night chasing away raccoons. Was terrifying. Gonna turn it into a simple horror game using only free assets. (Unless I can't find a racoon asset, then I may have to modify a fox one I found, or just use the fox) Gonna take a break from my bigger projects, and make it. Just one non-procedual environment, 2-3 enemy ai, and 2 players.

    • @ironboots
      @ironboots 4 месяца назад +1

      did you?

    • @rmt3589
      @rmt3589 4 месяца назад +2

      @@ironboots Not yet. There was an incident with Unity.

    • @taxesjuicebox
      @taxesjuicebox 2 месяца назад +1

      @@rmt3589 did you finish it yet?

    • @rmt3589
      @rmt3589 Месяц назад +1

      @@taxesjuicebox I need to. Need to learn Godot enough. Hyperfocusing on making a mon-type set of characters, have an elemental system, and am going through all the inspiration diligently. Already past 550 pokemon I think, and stopped the research today on Zoroark. (Same column as Ninetails and Lucario. Despise Lucario being one of my favorite program, never made the connection between him and the Tanuki Hengeyokai)

    • @lolzodolzo6407
      @lolzodolzo6407 14 дней назад +1

      ​@rmt3589 so much for an actually simple game😭😭 the game dev curse

  • @EmporiumofSound
    @EmporiumofSound 7 месяцев назад +2

    This was incredibly clear and far less code used than some of the other videos on youtube. Love this.

  • @saramostafa3700
    @saramostafa3700 2 года назад +9

    omg you are amazing , I saw a 17minute video trying to understand this and you made it so simple and you didn't even use raycast like omg

  • @Rosethesicko
    @Rosethesicko Год назад +8

    Amazing video man this helped me a lot, for my top down 2d RPG I wanted to lock rotation on the Y for smoother looking enemy movement.
    To do this I removed the last bit of code
    "transform.rotation = Quaternion.Euler(Vector3.forward * angle);" this doesn't lock rotation but prevents your enemy from rotating 😊

  • @gamesquad6743
    @gamesquad6743 2 года назад +12

    Awesome this is just what i needed, like im making a simple 2d game that needs enemies, currently all enemies shoot me even if i was at the start of level

    • @bblakeyyy
      @bblakeyyy 2 года назад +2

      glad to hear it! make sure to subscribe :)

    • @gamesquad6743
      @gamesquad6743 2 года назад +4

      @@bblakeyyy im already subscribed to ur main channel and your second channel

  • @valentinajara6597
    @valentinajara6597 Год назад +1

    OMGGGGG, THIS WAS EXTREMELY HELPFUL. THANK YOUUU

  • @andreysantana3433
    @andreysantana3433 Год назад +1

    simple to follow, full of good info and quick. Love the vid!

  • @north3198
    @north3198 27 дней назад

    very helpful and to the point thank you!

  • @Reina9
    @Reina9 Год назад +3

    Me pareció genial, siento que otros vídeos o lo hacían muy complejo o simplemente demasiado simple como para que este satisfecho con el resultado. Este vídeo me pareció rápido y que va directamente al grano aparte de explicar bien y claro lo que esta haciendo durante el trascurso del mismo. 10/10

    • @AlexanderEriksson-n3j
      @AlexanderEriksson-n3j 7 месяцев назад

      Yo no hablas espanol. Quiero una hamburguesa con patatas frites

  • @manunavoni7666
    @manunavoni7666 Год назад

    Wonderful tutorial, Definetly deserves more views.

  • @RufusWestendarp
    @RufusWestendarp 5 месяцев назад

    Used this for enemy super helpful love ur channel

  • @vadeeme95
    @vadeeme95 Год назад +1

    very nice tutorial, thanks!

  • @iglonudel1680
    @iglonudel1680 Год назад

    Super neat tutorial, I'm using it for an enemy :)

  • @greenblack9165
    @greenblack9165 Год назад +1

    love u, greetings from Poland

  • @newtiam3171
    @newtiam3171 2 года назад

    Nice 😀it's a great tutorial👌 thank you 💫

  • @RTPcanadaGames
    @RTPcanadaGames 8 месяцев назад

    im making a game about a frog with this mechanics.gunna be awesome. Using my own art. . .and got a crew member to help work on the poroject

  • @bansaribalar694
    @bansaribalar694 Год назад +1

    Nice Work

  • @RevaReefs
    @RevaReefs Год назад

    Thank you , great video.

  • @PxelBlade
    @PxelBlade 3 месяца назад

    ima use this for just a simple game where squares constantly spawn and you see how long you can survive for

  • @tourelle567
    @tourelle567 2 года назад

    Very usefull tutorial, thanks !

  • @biged606
    @biged606 Год назад +1

    Good job!

  • @Blockhead-xc3dq
    @Blockhead-xc3dq 2 года назад +1

    Awesome!

  • @dafe1115
    @dafe1115 Год назад

    Used it for an enemy you are amazing

  • @matheusbertos3303
    @matheusbertos3303 2 года назад +1

    Noice!

  • @harrisashraf7084
    @harrisashraf7084 Год назад

    nice :) i finally have a enemy that approaches me and kills me

  • @Mot0Mot0
    @Mot0Mot0 Год назад

    thx for this i love you

  • @javazombi
    @javazombi Год назад

    Thank you!

  • @jbot2288
    @jbot2288 Год назад +1

    I'm having an issue with the vector2 movetowards line of code, its giving me a cs7036 error saying something about max distance delta. any clues? anyways your previous tutorials have been great, and so far this is too! earned a sub you have helped me aton. 3:47 is were I am stuck

  • @K1ngCaden
    @K1ngCaden Год назад +2

    im getting the error saying " 'Transform' does not contain a definition for 'position' and no accessible extension method 'position' accepting a first argument type 'Transform' could be found"
    any way to fix this?
    edit: spelled position wrong fixed now

  • @NikolayAvanesyan-j5l
    @NikolayAvanesyan-j5l 5 месяцев назад

    Good job

  • @xxzz195
    @xxzz195 5 месяцев назад

    ty is very useful

  • @aaronmartinez3659
    @aaronmartinez3659 Год назад

    I´m using this on my 2nd "prototype game" where you get chased by some geometric shapes and you try to kill them

  • @gabrielRRR730
    @gabrielRRR730 Год назад

    Thank You

  • @mohammedabbas7030
    @mohammedabbas7030 Год назад

    very usefull thank you

  • @arcangel3sswa
    @arcangel3sswa Год назад +1

    Hello, I have this problem when I want to do the spawnEnemy.
    When I drag the object to reference the Player I get this error: "Type Mismatch". It's wrong?

  • @agustinquindimil6594
    @agustinquindimil6594 11 месяцев назад

    you're the best

  • @niuka8688
    @niuka8688 2 года назад

    thanks

  • @Mr.Sean.
    @Mr.Sean. 2 года назад

    This video fucking eazy and usefull, fucking love it

  • @hggpi
    @hggpi 2 месяца назад

    question about the distance or the movetowards.i dont know tbh
    basically if i want the whole thing to be on X axis only and i dotn want to use rigidbody to solve it. Can i do it somehow?
    Also the if statement wont really work in a 2d platformer style game from my experience because the Y axis is equal and the transform.pos has 2 axises right.
    So how do iput the whole thing on X
    i tried looking around on forums but i didnt really find an answer.

  • @GrumpyIdiot
    @GrumpyIdiot Год назад

    Amazing and freaking easy
    But what if I want the enemy to go back to their place when they stop chasing the player?

  • @chelchkik
    @chelchkik Месяц назад +2

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class Enemy : MonoBehaviour
    {
    public GameObject player;
    public float speed;
    private float distance;
    public float distanceBetween;
    void Start()
    {

    }
    void Update()
    {
    distance = Vector2.Distance(transform.position, player.transform.position);
    Vector2 direction = player.transform.position - transform.position;
    direction.Normalize();
    float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    if (distance > distanceBetween)
    {
    transform.position = Vector2.MoveTowards(this.transform.position, player.transform.position, speed * Time.deltaTime);
    transform.rotation = Quaternion.Euler(Vector3.forward * angle);
    }
    }
    }

    • @CosmicBacon0
      @CosmicBacon0 Месяц назад +1

      THANK YOU SO SO SO SO SO SO MUCH YOU SAVED MY LIFE

  • @tntdawolf7650
    @tntdawolf7650 Год назад

    This is great I'm using it for a zombie.

  • @ProBlockHead
    @ProBlockHead 2 года назад +1

    Do you know of any way I could slow down how fast the enemy rotates? Great tutorial! 👍

    • @morebblakeyyy
      @morebblakeyyy  2 года назад

      Take a look into Lerp and Slerp functions, there's a bunch of great info about rotation smoothing👌

  •  2 месяца назад

    Is it possible for enemy ai to be drawn to multiple players? What would the code look like?

  • @nafisforkan5188
    @nafisforkan5188 Год назад

    How would I apply an offset to the position I want the AI object to go towards? Like I can apply an offset but I need the offset to change depending on the direction the player approaches the object. I can't get normalized to work.

  • @dryzoFy
    @dryzoFy Год назад +1

    Vector2.Distance doesnt work for me
    pls help. btw im using 2021.3 version

  • @theartframe9596
    @theartframe9596 7 месяцев назад

    This is amazing🥲 ! Thank you I’m gonna give you credit in my game.. I’ve used your info before

  • @ZFLT
    @ZFLT Год назад +1

    A useful and fun video from which I have benefited a lot but how can I make the enemy skip the walls and not hit them?

    • @morebblakeyyy
      @morebblakeyyy  Год назад +1

      You’ll need to use pathfinding for that

    • @morebblakeyyy
      @morebblakeyyy  Год назад +1

      Or if you don’t care about obstacle avoidance and want your enemies to just pass through them you can set your enemy’s collider to a trigger and just check for collision on the playet

    • @ZFLT
      @ZFLT Год назад +1

      Thank you I've got the answer 😊I didn't expect you to be quick to reply, Wow.😅

  • @RandomProductionszsz
    @RandomProductionszsz Год назад +1

    Great Tutorial! But for unknown reasons adding like 5-7 enemies with this script attached makes my game massively slow down in frame rate. Unchecking the script everything runs smooth. Any ideas for this one? No errors in the console either.

  • @ihx7
    @ihx7 Год назад

    i have an issue when i try to shoot my enemy i hit the collsion for detecting if they player is nearby but when i try to check what collider it is it doesnt work

  • @maliktot7182
    @maliktot7182 Год назад

    Great tutorial, thank you, but I have an enemy that shoots from distance and I wanted to ask, is there a way to make the enemy stop at as soon as he reaches a certain area?

    • @morebblakeyyy
      @morebblakeyyy  Год назад +1

      Take a look at Vector2.Distance
      You can use this in if statements to check for distance between to objects, and change behaviour upon that

  • @peterrobson6958
    @peterrobson6958 Год назад

    Hey, very helpful video! Although I'm getting a problem with the AI just moving on it's own in a straight line and not starting where it is placed when the play button is pressed. Do you know anything about this that could help?

    • @BBore
      @BBore Год назад

      Gravity?

  • @umutkilexter9351
    @umutkilexter9351 Год назад

    Teşekkürler

  • @olioo1234
    @olioo1234 Год назад

    how can i check if the player is on the right or left of a given object so i can relate to each differently?

  • @swantholomew4809
    @swantholomew4809 Год назад

    Hey great video it really helped but Im having issues as soon as i add colliders into the mix. The enemy doesnt seem to want to follow me anymore as soon as we touch. Have you experienced something similar and could mabye help?

    • @TheRealBillyB
      @TheRealBillyB Год назад

      if you mean that when you add a rigidbody2d and smack the enemy that it just flies off in to oblivion, try adding linear drag of like 5 or so

  • @clownfr3d
    @clownfr3d Год назад

    I can't change the enemy speed. It will always have the same speed no matter if I change it

  • @jaymodz3568
    @jaymodz3568 2 года назад +1

    What visual studio add-on u using which shows u things u can add like intellisense?

    • @morebblakeyyy
      @morebblakeyyy  2 года назад

      It’s just the most recent version of visual studio. It’s scary sometimes how accurate it is hahaha

    • @jaymodz3568
      @jaymodz3568 2 года назад

      @@morebblakeyyy oh ok, I'm still using 2019 that's why haha

    • @jbot2288
      @jbot2288 Год назад

      @@morebblakeyyy lol I thought you were using copilot

  • @CheesyWasHere
    @CheesyWasHere 2 года назад

    How do I make so that it works w/ your previous tutorial on to make a basic 2D Game

  • @fryptompt
    @fryptompt Год назад +1

    how do I add collision in this enemy AI, right now it just goes through walls :/

    • @takivazquez2836
      @takivazquez2836 Год назад +1

      Box Collider

    • @fryptompt
      @fryptompt Год назад

      @@takivazquez2836 bruh it is not working that is why i asked -_-

    • @AVGVA
      @AVGVA Год назад +1

      the walls also need to have a collider you know that right? and also check if the collider is only a trigger or not

  • @Augustyand
    @Augustyand 2 года назад

    Is there any way to look it to only the x position for movement thanks

  • @ХоаХоДык
    @ХоаХоДык Год назад

    The video is great!
    Please check again, I can't download the project

  • @sandwick4147
    @sandwick4147 9 месяцев назад

    hello! i was trying to do this for one of my school assignments with no coding knowledge, I'm not able to get any of my words to match the mint hue that words like GameObject and vector2 have, was there something i had to set up before hand? im using 2019 microsoft visual studio for this, i dont know if the program is outdated or if this is a different program your using in the video, any suggestions would be great, thanks!

    • @editsbyr1
      @editsbyr1 6 месяцев назад +1

      nope its just that he uses a lot of coding so his visual studio remembers , its okay if yours doesnt have colors or suggestions !

  • @graygz8326
    @graygz8326 Год назад

    hi ! nice tuto ! is anyone got a problem with the quaternion.Euler and the vector3 ? this can't be converted no ? tx

  • @lehmspielt
    @lehmspielt 2 года назад

    Do you know a way i could stop it from following the player in the air?

  • @HylianLegend
    @HylianLegend 2 года назад

    Great tutorial, but is there a way to make the enemy box collider collide with walls? Right now my enemies are working great but they can go through walls the player cannot.

    • @morebblakeyyy
      @morebblakeyyy  2 года назад

      To do this you need to move your enemies through a rigidbody. Rigibody.add force or rigidbody.velocity

    • @HylianLegend
      @HylianLegend 2 года назад

      @@morebblakeyyy Thanks!

  • @SantaGamerYoutube
    @SantaGamerYoutube 2 года назад

    The enemy is flipping to the wrong direction. I tried adding the enemy in a empty game object and turning it too but it would always snap back

  • @thatwafflerightthere2098
    @thatwafflerightthere2098 2 года назад +1

    So my enemy is going really slow for some reason, I am using it with gravity and a rigid body so I don’t know if that is what is effecting it but anyone got any tips?

    • @svardleo5275
      @svardleo5275 Год назад +1

      Change the speed when you click the enemy and scroll down to the script?

    • @svardleo5275
      @svardleo5275 Год назад +1

      or on the float speed do = any number

  • @zhousongjiang
    @zhousongjiang 2 года назад

    Hi! I followed your code, and finally got the opposite result and couldn't reproduce your effect.
    I double checked the code and made sure there were no doubts. The code does not report an error, but it does not achieve your effect.

    • @RimuruDev
      @RimuruDev Год назад

      Good day, RimuruDev channel is in touch. This is how it works: (distance > 4).

  • @BillyBBrooks
    @BillyBBrooks Год назад

    for some reason when i use the code in the video to the point where it just chase without rotating it says in the console "the name 'distance' does not exist in the current context any tips on how to fix it

    • @palomarivera5475
      @palomarivera5475 Год назад

      you need to declare the variable distance first, outside of the void udpate.
      public class chaser : MonoBehaviour
      {
      private float distance;
      etc.

  • @peachy8335
    @peachy8335 Год назад +1

    cann you make it wherre it rrestarts when you touch it

    • @neapy9832
      @neapy9832 Год назад +1

      You would need to add this piece of code to your script, which should go under the void Update() method:
      //Checks for collisions.
      private void OnCollisionEnter2D(Collision2D other)
      {
      //This Checks if your player has the tag "Player".
      if (other.gameObject.CompareTag("Player"))
      {
      //If the collided object has the tag of Player, then the scene loads the active scene, causing a restart.
      SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
      }
      }
      To get access to the scene management, you need to import the library for it, by using this:
      using UnityEngine.SceneManagement;

    • @peachy8335
      @peachy8335 Год назад

      @@neapy9832 your a legend

  • @JohnCarter-lg2tb
    @JohnCarter-lg2tb 7 месяцев назад

    Anyone had error code cs1503 at 2minutes 47 seconds

  • @bimaa.s9165
    @bimaa.s9165 Год назад

    does this also work to make friendly character following us?

  • @RimuruDev
    @RimuruDev Год назад

    Good afternoon, the RimuruDev channel is in touch. If the code doesn't work for you, fix it like this) : (distance > 4).

  • @slyfalkon9220
    @slyfalkon9220 Год назад

    how do you store the public GameObjekt in a prefab?

    • @jbot2288
      @jbot2288 Год назад

      drag the gameobject into the assets section at the bottom.

  • @DaMosseShorts
    @DaMosseShorts Год назад

    Can Someone give me the script I have Errors :(

  • @user-fm1nb6qt4l
    @user-fm1nb6qt4l Год назад

    2:47

  • @noobmaster6032
    @noobmaster6032 2 года назад

    the speed is so slow how can i change it thanks

    • @svardleo5275
      @svardleo5275 Год назад

      public float speed = whatever number;

  • @SirBobCheeese
    @SirBobCheeese Год назад

    it tells me that i dont have a transform

    • @jbot2288
      @jbot2288 Год назад

      Make The capital T a t

  • @mmstudios8887
    @mmstudios8887 Год назад

    Am i the only one who this didn't work for?

    • @morebblakeyyy
      @morebblakeyyy  Год назад

      What issues are you having?

    • @mmstudios8887
      @mmstudios8887 Год назад +2

      @@morebblakeyyy Figured it out, I'm a moron and put 2: " ; "

  • @kennethbradley6392
    @kennethbradley6392 2 года назад

    😌 P*R*O*M*O*S*M!!