2D PLATFORMER PATROL AI WITH UNITY AND C# - EASY TUTORIAL

Поделиться
HTML-код
  • Опубликовано: 4 июн 2024
  • In this easy unity tutorial, I will bring you through the process of creating a simple 2D patrolling npc with Unity and C# !
    The character will detect the edge of the platform, and turn on his heels, moving in the opposite direction ! This will be achieved using rays !
    Here is the LINK to the AI ongoing series : • AI TUTORIALS WITH UNIT...
  • ИгрыИгры

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

  • @ShadowStrider09
    @ShadowStrider09 6 лет назад +157

    If you want to detect a specific layer do this
    int layer_mask = LayerMask.GetMask ("Ground");
    RaycastHit2D groundinfo = Physics2D.Raycast (groundDetection.position, Vector2.down, distance, layer_mask);

    • @MarkTheMadMan
      @MarkTheMadMan 4 года назад +13

      That came back with an error for me. So i replaced it with:
      RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, 2.0f, LayerMask.GetMask("Ground"));
      and that worked

    • @achucxeno3588
      @achucxeno3588 3 года назад +3

      @@MarkTheMadMan OOOOOOHHHHH MYYYYYYY GOD THANK YOU THANK YOU THAAAANKKK YOUUUUUUUUUUUUUUU

    • @panttrans8448
      @panttrans8448 3 года назад +1

      @@MarkTheMadMan Thank you markyboi28

    • @motimimon1
      @motimimon1 3 года назад

      you freaking rock. this helps if the raycast length is not configuring for any1

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

      if anybody has errors with this one, the reason is because creating the int and assigning layer number should not be used together
      You just define the int outside of Start and Update methods, (for example - int layernum;)
      and then you assign the layer number inside the Start method (layernum = LayerMask.GetMask ("AnyLayer");)
      Now just use this int in Raycast (RaycastHit2D groundinfo = Physics2D.Raycast (groundDetection.position, Vector2.down, distance, layernum);)
      After this is just explanations why it works this way and why this way is better, read if interested.
      The reason why you can't just assign it right away, is because GetMask() method can only be used inside Start(), Update(), and almost any other methods (including yours). This is because Unity works unlike simple C#. Unity doesn't just run the code, it instead relies on built-in methods of MonoBehaviour class, that's where all processes are made. So outside them, is just data that you can store, to later use, so no method calling outside of them.
      Basically, you can't use any Monobehaviour methods, unless you are in another method in Monobehaviour. (Sorry for repeating the word method so much)
      Now, the reason why this way is slightly better than what Marky wrote,
      if you assign it right in the Raycast(), then every time it's called (in this case it's in Update(), so every frame) you run GetMask().
      But when you use GetMask() in Start(), to assign the result to a variable, the method is called just this one time, with then referencing the variable. Accessing the variable takes less resources than calling the method each time.
      The difference is not really big, but in actual game such details can make game faster. Just know that if you need to access the result of a method, that doesn't need to be constantly checked, store it inside a variable (of course if possible)

  • @cristiangarcia9009
    @cristiangarcia9009 6 лет назад +125

    OMG!!! Thank you, you´ve saved me, there is a lot of large, annoying and useless tutorials about enemy AI patrol, but this is short and works prefectly on my project! THANKS :DD

    • @mozan47906
      @mozan47906 5 лет назад +4

      True. His videos are to the point.

    • @Someone-kw6mw
      @Someone-kw6mw 3 года назад

      Brackeys tutorial on this is also poop 💩💩💩💩

    • @user-vg4on5cj8b
      @user-vg4on5cj8b 3 года назад

      @@Someone-kw6mw
      Brackeys tutorials are always poop

  • @criticalhittcg5637
    @criticalhittcg5637 4 года назад +3

    Dude, thank you, Noah! I've been looking into how to do this for 3 hours with no results till now, and all I had to do was go back to your trustworthy tutorials.

  • @maddened3746
    @maddened3746 3 года назад +1

    THANK GOD there's someone making tutorials who gets straight to the point.... no extra lengthy lectures just for 2-3 lines of code...
    Thanks bro, this helped a BUNCH!

  • @Mimikyuke
    @Mimikyuke 3 года назад +2

    Finally, I've gone through tutorial after tutorial and nothing has worked until now. Thank you!

  • @megtwin
    @megtwin 5 лет назад +1

    Love your videos, so well structured and clearly explained without getting too difficult, keep up the great work!

  • @ajayvijayh
    @ajayvijayh 6 лет назад +11

    Thank you so much! I like the way you make tutorial...you first explain the concept and then implement it.keep it up

  • @stickbro4118
    @stickbro4118 5 лет назад +1

    Thanks for the tutorial BTP! I used it to work on a mario clone game when the tutorials I used to make the enemy weren't as helpful.

  • @jahmaijones6331
    @jahmaijones6331 5 лет назад

    Straight forward and easy to understand thank you! i had to attempt it twice, first time i did it, something was intercepting with previous code i had written on my character movement script but now it works like a charm! thanks

  • @IsoRen245
    @IsoRen245 4 года назад +1

    This tutorial is exactly what I was looking for and it works great! Thank you!

  • @mozan47906
    @mozan47906 5 лет назад +6

    Thanks, man I was searching for this movement.

  • @CococuteManaloto
    @CococuteManaloto 6 лет назад

    I have been watching a lot of Unity tutors here and so far you are one of the best, easy to follow and noob friendly. I hope you cover some mobile inputs and controls too.

  • @simoncodrington
    @simoncodrington 5 лет назад +5

    Nice stuff man. Easy way to create a patrolling enemy. Wish I'd seen this before I went and wrote up my own version :)

  • @m3agle
    @m3agle 5 лет назад

    You the best unity youtuber, seriously! Love your videos keep up the good work!

  • @matthewcleere2061
    @matthewcleere2061 5 лет назад

    Absolutely fantastic video! Excellent walk explanations and it really helped me understand everything. So easy to follow also! Thank you so much!

  • @derrickshowproductions3010
    @derrickshowproductions3010 5 лет назад

    I think your tutorials are very useful and helpful as they are simple and easy to understand.
    There tends to be not alot of unesscary coding involved,

  • @Michael-The-Composer
    @Michael-The-Composer 5 лет назад

    Nice video! Thanks for this code, it really saved my life. I used it with a player that I could move and make it jump (the script for the player movement and jumping being your 2D character controller with double jump/triple jump).

  • @danielhetrick677
    @danielhetrick677 5 лет назад +1

    Wonderful tutorial! Truly helped me. P.S. - Put some of those foam wall thingys in your recording room to get rid of echo.

  • @Dr.Thriller
    @Dr.Thriller 5 лет назад +1

    Thanks this helped a lot,
    although I had a few complications, I managed to fix it.

  • @sumitmaurya2119
    @sumitmaurya2119 4 года назад

    Thankyou so much, was stuck with enemy code, you cleared it way smoothly.... 😇

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

    This is exactly What I needed. Simple and work perfectly. Thank you so much!

  • @DieserJunge89
    @DieserJunge89 4 года назад

    Thanks for these videos! They are helping me a lot right now.

  • @mikeymoo4681
    @mikeymoo4681 6 лет назад

    Thank you so much you saved me hours i didn't know what a ray was

  • @sosasees
    @sosasees 4 года назад

    Thanks very much! I needed this for my game!

  • @bunggo9914
    @bunggo9914 6 лет назад

    I always love your AI tutorials video...it gives me the idea that making AI is not as hard as I think...

    • @Blackthornprod
      @Blackthornprod  6 лет назад

      Exactly :) ! AI, when broken down can be very simple ! My next AI video will probably cover adaptable AI (in other words the enemy or npc will change behaviour depending on what the player does ) ! Stay tuned :)

    • @tiui2371
      @tiui2371 6 лет назад

      That is more a set behaviour than AI, let me explain: Id consider an AI something that: with inputs can make a decision on what to do, like run, attack or be passive. That is not making any decisions its just checking if it collides with the ground and if it does not it turns 180 degrees.
      A true in game AI (not like true AI that can think and make phrases...) would be more like a neural network. That just gave me an idea.

  • @betosanchez9932
    @betosanchez9932 3 года назад +1

    Ty for being my guide into this new world u are the best dude, greets from Ecuador

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

    Thanks a ton. Was having a hard time figuring this out by myself

  • @glennenri
    @glennenri 3 года назад

    NICEEEEE! This will be useful in making my game. As always, you heled me a lot. Thankyou!

  • @thetelpho2176
    @thetelpho2176 3 года назад

    Worked like a charm! Thanks!

  • @davidfu8174
    @davidfu8174 5 лет назад

    Awesome tutorial!

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

    You are a Godsent! Thank you!!
    I've been struggling with this forever and ever!! Now I can finally move on!

  • @zackweber231
    @zackweber231 4 года назад

    Such wow! Your tutorials are great!!

  • @kinghasni2313
    @kinghasni2313 4 года назад

    Like Always Love to Watch Your Tutorials .

  • @khangmai3151
    @khangmai3151 5 лет назад

    Thanks for helping, mr. prod

  • @ricci3950
    @ricci3950 4 года назад +1

    Thanks for the tutorial. What should I do if I want that character to stop patrolling and attack the player when it's near?

  • @InSTaDev
    @InSTaDev 5 лет назад

    big props dude
    HUGE TIME SAVER

  • @TheYonderlander
    @TheYonderlander 5 лет назад +2

    This is exactly what I needed, thank you! Though, it would be super helpful if you posted a github of the code so it'd be easy to test out said code. Otherwise, thank you!!

  • @aarenkazhmir868
    @aarenkazhmir868 3 года назад

    It helped me to place the ground detection gizmo in front of the ai , and placed inside of the platform.

  • @kokhaofong8262
    @kokhaofong8262 5 лет назад

    simple and easy to understand. thanks.

  • @lukepaluso9863
    @lukepaluso9863 5 лет назад

    that code is elegant!!!! ありがとう!

  • @xeviusUsagi
    @xeviusUsagi 3 года назад +4

    I have a little problem,
    I want the enemy to start by going to the left
    but if I change the direction where he goes: transform.Translate(Vector2.right * speed * Time.deltaTime);
    to left: transform.Translate(Vector2.left * speed * Time.deltaTime);
    the character will detect the end of the platform
    but he will start going crazy constantly switching around and being stuck in place since he's turning really fast constantly
    moving him back will make him go left again but as soon as he find the end of the platform he goes crazy again
    I did change Moving right to left just to be sure: MovingRight = left;
    but this didn't fix the problem (but if I make the enemy go right like in the video everything works perfectly)
    so, what do I have to change to solve this problem?
    (I will now post the entire code just in case it's needed)
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class Rat_Patrol : MonoBehaviour
    {
    public float speed;
    public bool MovingRight = false;
    public float RayDistance;
    public Transform groundDetection;
    private void Update()
    {
    transform.Translate(Vector2.left * speed * Time.deltaTime);
    RaycastHit2D groundinfo = Physics2D.Raycast(groundDetection.position, Vector2.down, RayDistance);
    if(groundinfo.collider == false)
    {
    if(MovingRight == true)
    {
    transform.eulerAngles = new Vector3(0, -180, 0);
    MovingRight = false;
    }
    }
    else
    {
    transform.eulerAngles = new Vector3(0, 0, 0);
    MovingRight = true;
    }

    }
    }

  • @bunthaideng2492
    @bunthaideng2492 3 года назад +2

    I am new to unity.
    To move an object, there are many ways to implement it.
    For example, using
    - transform.Translate ( ... )
    - rigidbody.velocity = ....
    - rigidbody.AddForce ( ... )
    Not only moving but also turning the object.
    For example, using
    - FindObjectOfType().flipX = boolean
    - rb.transform.localScale = new Vector3(Math.Abs(rb.transform.localScale.x), ....)
    - transform.eulerAngles = new Vector3(0, -180, 0);
    There are many more cases, but I talk only 2 cases.
    Is there a standard way to implement it?

  • @scratchtutorials1068
    @scratchtutorials1068 3 года назад

    Thank you so much for making this

  • @tectonicplating
    @tectonicplating 4 года назад +1

    Great video!

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

    nice tutorial, also if you make a front check object and flip direction when it detects a wall, you can make it avoid WALLS too, which is important.

  • @nicholascarson2554
    @nicholascarson2554 4 года назад

    What if I wanted the enemy to move along the y-axis instead of the x-axis is that possible and how do I go about doing that? Would I just use up and down instead of left and right?

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

    Thank you for the code. Not sure what I did but now my enemy is just flipping in the same place on the platform and moves when my player interacts with it to beyond it’s restricted platform. Any idea where I could have gone wrong? Please

  • @johndough7479
    @johndough7479 5 лет назад

    Fantastic videos!

  • @eddie1591
    @eddie1591 3 года назад

    worked perfectly thank you so much

  • @apenasumrabisco2760
    @apenasumrabisco2760 5 лет назад

    This is amazing, it worked perfectly, but since I'm working with lights this change doesn't work, how do I change the flip through the X axis?

    • @haikermaiker
      @haikermaiker 5 лет назад +1

      you need to acces the sprite renderer of your objecct and use spriterenderer.FlipX=true or false depending on the case

  • @hxmr-kc2fh
    @hxmr-kc2fh 3 года назад

    Thank you! that worked very well.

  • @salahqamachi2084
    @salahqamachi2084 4 года назад

    thank you so much it cant get any easier than that, again, thank you

  • @barsaliaksu2963
    @barsaliaksu2963 4 года назад

    Nice tutorial bud. Thanks for video :))

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

    Freaking amazing and easy to implement!

  • @Furv_Liea
    @Furv_Liea 5 лет назад

    what if i only want the direction to change how do i do that? i can use the if(movingRight) statement but that thing will keep on looping and i have a script that can follow the player and advise?

  • @dylanprice893
    @dylanprice893 4 года назад +1

    for: if (movingRight == true) or if (movingRight == false),
    you can just write: if(movingRight) for true and if(!movingRight) for false.

  • @amgames5638
    @amgames5638 4 года назад

    For cleaner code, instead of == false, == true, just put if(!groundInfo.collider) and if(movingRight). Just typing the bool automatically translates to == true.

  • @akenschilp3830
    @akenschilp3830 5 лет назад +6

    Hey Black, question how can i do it that the Ai moves like this in this tutorial and he dedects the wall in front of him to walk away from it?

    • @elloRUBICON
      @elloRUBICON 5 лет назад +2

      I have this same issue, anyone got ideas?

    • @TF4Hikari
      @TF4Hikari 5 лет назад +4

      same. I hate these magic simple trick codes. They just tell you dumb thing. Like, hey! Let's make moving enemy, to bad he didnt say how to code actual enemy that interacts with player

    • @bringatowel143
      @bringatowel143 5 лет назад +1

      RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, distance); is the code he gives us and instead of Vector2.down try Vector2.right or Vector2.left but those will be dependent on which direction they are moving and the if statement below would be switched to if(groundInfo.collider == true)

  • @gabrielnovaes664
    @gabrielnovaes664 6 лет назад

    very good tutorial !!!!!

  • @marceloo7278
    @marceloo7278 4 года назад

    Thank you soo much

  • @mathijstjeerdsma7181
    @mathijstjeerdsma7181 6 лет назад +1

    Keep up the good work! Love your vids bro!

  • @user-uc4ui6mv1j
    @user-uc4ui6mv1j 6 лет назад

    would you please tell us how to make it walk around the platform thanks in advance

  • @admulberg
    @admulberg 5 лет назад

    Thank you! As a user Tiui50 mentioned below, the code could be simplified to :
    public class PlatformPatrol : MonoBehaviour
    {
    public float speed;
    public float detectorDistance = 2f;
    public Transform groundDetector;
    private void Update()
    {
    transform.Translate(Vector2.right * speed * Time.deltaTime);
    RaycastHit2D groundInfo = Physics2D.Raycast(groundDetector.position, Vector2.down, detectorDistance);
    if (!groundInfo.collider)
    {
    transform.eulerAngles = new Vector3(0, transform.eulerAngles.y - 180, 0); // Here we just rotate the character based on his current angle
    }
    }
    }

  • @henryjohn6244
    @henryjohn6244 5 лет назад +6

    Can you make enemy fly up and down please !

  • @1DrowsyBoi
    @1DrowsyBoi 3 года назад

    Good video, but it feels a little more convoluted than necessary with the extra game object, since we can just get the edge of our character's sprite/hitbox with a few variables.

  • @samed7418
    @samed7418 3 года назад

    best tutorial ever

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

    I'm using this script myself, but whenever the player comes into contact with any of my patrolling enemies, they freak out, starting to move in small arcs up and down along the ground, kinda like jumping frogs I guess if that makes sense, which can make the raycast faulty. How do I resolve this?

  • @mutaz9025
    @mutaz9025 5 лет назад

    this doesn't work if I add polygon collider to world the enemies still moving how to fix that ??

  • @vrajsoni7610
    @vrajsoni7610 4 года назад

    Can you make a video to confine the enemy patrol upto a limit on x-axis like from x=0 to x=4 only and also how to confine the vertical movement

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

    Simple yet genius

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

    I havent tried this yet but I have a doubt. Does the detection work for colliders with isTrigger set to true?

  • @Noyader
    @Noyader 6 лет назад

    tnak youuuuuuu this helped so much

  • @bestdaddyoftheyear
    @bestdaddyoftheyear 3 года назад +8

    Hiya! Where and how did you use the "distance" ?

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

      He said that it wasn't entirely necessary in this case. In the code line "RaycastHit2D groundInfo = Physics2D.Raycast(detectGround.position, Vector2.down, 2f);" he said that if you don't want to use a static value for the distance (2f in this case) that requires you go into code and manually update it every time you want to change it, then you can create a variable that can be updated from the Unity Inspector directly, saving you the time of having to open up the code again each time.

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

    Awesome and very simple.
    Just one update i would like to add.
    Instead of adding moving right or left function it's easy to just use rotate function.
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class Patrol : MonoBehaviour
    {
    public float speed;
    public float distance;
    public Transform groundCheck;
    // Update is called once per frame
    void Update()
    {
    transform.Translate(Vector2.left * speed * Time.fixedDeltaTime);
    RaycastHit2D groundInfo = Physics2D.Raycast(groundCheck.position, Vector2.down, distance);
    if(groundInfo == false)
    {
    transform.Rotate(0f, 180f, 0f);
    }
    }
    }

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

      I know this was a year ago, but I have to say thank you for this!

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

    So useful man
    Your video help me a a lot!!!
    Big thank for my man.

  • @Sheldinator
    @Sheldinator 4 года назад

    when i copy and paste this platform it does not move. only the first one that i coded works. isnt their a way to copy this or do i have to this over and over again?

  • @jakepearce4949
    @jakepearce4949 5 лет назад +1

    Can you make one that turns when there is a wall

  • @miloverreijt6396
    @miloverreijt6396 5 лет назад

    He amazing video i used it in a game i made but how do u make it so he turns if collision with a box or other obstacle

  • @engmazen6557
    @engmazen6557 6 лет назад

    thank you very
    much

  • @patrushtamang7800
    @patrushtamang7800 6 лет назад

    you are awesome!!!

  • @gohelboy
    @gohelboy 4 года назад +1

    Good video but if i apply camera confiner then this is not working ! Any fix

  • @djinterghost
    @djinterghost 5 лет назад +1

    Excellent tutorial but this seems to only work with a box collider. How could I implement this working with a tilemap collider used by composite collider? My enemy sprite is not detecting the collision/walls/ground/platforms. Thanks!

    • @shiftrapidz3426
      @shiftrapidz3426 5 лет назад

      I'm having the same problem too, could really use some help

    • @djinterghost
      @djinterghost 5 лет назад

      @@shiftrapidz3426 I worked out that this only works if there's a gap in your platform the object is on. it has to hit a tile where there is no ground for this to work but as long as it hits a tile with no ground on 1st cycle it works with wall object also, very weird.

    • @djinterghost
      @djinterghost 5 лет назад

      @@shiftrapidz3426 set the distance to 1 and see if that works for you

    • @shiftrapidz3426
      @shiftrapidz3426 5 лет назад

      Alright I'll try it

    • @TF4Hikari
      @TF4Hikari 5 лет назад

      I wish this would work with box collider. When i add box collider it just moves forward to infinity

  • @motimimon1
    @motimimon1 3 года назад +1

    it seems that te ray is always casting for an infinite length. This collides with the lower platforms. can any1 here help me with this?

  • @kadinstarr8486
    @kadinstarr8486 3 года назад

    Thanks so much!!!

  • @Odaznarak
    @Odaznarak 5 лет назад +1

    My camerabounds has a collider in it and because of it the AI doesn't flip what should I do to exempt that collider?

    • @sentinelmusic107
      @sentinelmusic107 4 года назад

      Set the collider to the Ignore Raycast layer.

  • @chronabigaming509
    @chronabigaming509 5 лет назад +2

    i first could not do it and felt soo bad then i looked at the video properly and found out i typed the if statement wrong xD

  • @gusthegiraffe7302
    @gusthegiraffe7302 5 лет назад +2

    hey could you make a video showing how to do the enemy followin the player and looking his at direction??

    • @massi368
      @massi368 5 лет назад

      YES, I make a 2D platformer and i follow your tuto the enemies follow the player but i dont know how to make him look to the player when it's in the opposite direction

  • @PraneshArry
    @PraneshArry 6 лет назад +1

    BlackThornProd FTW!!

  • @vikasagrawal6074
    @vikasagrawal6074 6 лет назад

    Dude u have a great art style!! I just loved it!!

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

    Nice A.I. NPC!

  • @lorann2018
    @lorann2018 5 лет назад

    awesome

  • @bluchickenstudios9957
    @bluchickenstudios9957 6 лет назад

    Cool and I like the videos audio

  • @pedrokot
    @pedrokot 3 года назад

    i would like to know how to add somekind of timer after reaching the edge of the platform, like stading still for 2s, and begin patrolling again, any ideas? thanks

  • @kressckerl
    @kressckerl 6 лет назад +1

    Wouldn't it be better to do it in fixed Update?

  • @rhythmandblues_alibi
    @rhythmandblues_alibi 3 года назад

    Wow it works!! Thank you ^_^

  • @TheTrolderia
    @TheTrolderia 3 года назад

    In a 2d top down game, how do i make my AI walk random between 1-5 sec and then stop for 1-3 sec, and then walk again? :)

  • @jessedeklein7542
    @jessedeklein7542 4 года назад

    can this script be ajusted for up and down movement aswell?

  • @johndough7479
    @johndough7479 5 лет назад +8

    High times: try recreating an Explosive sheep from Worms using this lesson as an exercise. =)

  • @hrishikeshgarud7177
    @hrishikeshgarud7177 6 лет назад

    THANK YOU!!!!!!!

  • @user-hl7lr8ld2i
    @user-hl7lr8ld2i 5 лет назад

    cool but i made a different one, i had 2 emptygame objects with box colliders with a tigger and if the trigger is touched the player will turn, in that way you can choose were the player will turn