How to make AI Turret Bots in UNITY - 2D

Ойындар

Consider donating to help me keep this channel and website alive : paypal.me/supportTheGameGuy 💖
In this video im gonna show you how to make AI bots that detect the player within some range and starts shooting when the player enters that range.
but the player can avoid them by hiding behind the platforms and walls.
If you want to learn more about the shooting and fire rate check out this great tutorial by brackeys :
• 2D Shooting in Unity (...
and if you have any questions leave them down in the comment section and Subscribe to my youtube channel if u haven't already.
THANKS!

Пікірлер: 91

  • @BobStroff
    @BobStroff4 жыл бұрын

    i looked so long for an tutorial like this thanksss

  • @beastmasterbg
    @beastmasterbg2 жыл бұрын

    fast and simple to understand and to the point! Thank You !

  • @Wormhole_Garden
    @Wormhole_Garden2 жыл бұрын

    This helped so much, thank you for your expertise!

  • @godfather8906
    @godfather89064 жыл бұрын

    Thanks dude for awesome tutorials. 👌👌

  • @aldescora
    @aldescora2 жыл бұрын

    Was exactly what I was looking for, only thing that messed me up was that the barrel would flip when I started it, so just had to change which side of my sprite was facing up (cause it was a rectangle) Other than that, straight to the point and great tutorial!

  • @StickyLabDev

    @StickyLabDev

    2 жыл бұрын

    i still failed

  • @stbny4444
    @stbny4444 Жыл бұрын

    Great tutorial. Thanks!

  • @jeffzak6790
    @jeffzak67904 жыл бұрын

    Really good tutorial! Thank you. Worked perfectly.

  • @StickyLabDev

    @StickyLabDev

    2 жыл бұрын

    doesnot work now 2019

  • @sliceggjd

    @sliceggjd

    2 жыл бұрын

    @@StickyLabDev it does

  • @harrythegamer8288
    @harrythegamer82883 жыл бұрын

    ive been trying to do this for months thanks

  • @gbaldessari
    @gbaldessari2 жыл бұрын

    Thanks u broo, i love the video

  • @lostlakeboy4765
    @lostlakeboy47654 жыл бұрын

    Realy good. thanks.

  • @homiek5974
    @homiek5974Ай бұрын

    thanks man

  • @macros3570
    @macros35703 жыл бұрын

    thank you so much

  • @aabdo9879
    @aabdo98794 жыл бұрын

    using System.Collections; using System.Collections.Generic; using UnityEngine; public class turretFunc : MonoBehaviour { public float Range; public Transform Target; bool Detected = false; Vector2 Direction; public GameObject Gun; public GameObject bullet; public float FireRate; float nextTimeToFire = 0; public Transform Shootpoint; public float Force; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { Vector2 targetPos = Target.position; Direction = targetPos - (Vector2)transform.position; RaycastHit2D rayInfo = Physics2D.Raycast(transform.position,Direction,Range); if (rayInfo) { if(rayInfo.collider.gameObject.tag == "Player") { if (Detected == false) { Detected = true; } } else { if (Detected == true) { Detected = false; } } } if (Detected) { Gun.transform.up = Direction; if(Time.time > nextTimeToFire) { nextTimeToFire = Time.time + 1 / FireRate; shoot(); } } } void shoot() { GameObject BulletIns = Instantiate(bullet, Shootpoint.position, Quaternion.identity); BulletIns.GetComponent().AddForce(Direction * Force); } private void OnDrawGizmosSelected() { Gizmos.DrawWireSphere(transform.position, Range); } }

  • @StickyLabDev

    @StickyLabDev

    2 жыл бұрын

    dang ,thanks

  • @warmasterkyst7518

    @warmasterkyst7518

    Жыл бұрын

    Bro thx u

  • @dontCallMe..

    @dontCallMe..

    Жыл бұрын

    u save 14 minutes from my life thx

  • @arczio3226
    @arczio32264 жыл бұрын

    Thanks

  • @mailmike933m
    @mailmike933m4 жыл бұрын

    Do u mind if i can have the complete project and assets or just the turret bot?

  • @hassanmaswedish2290
    @hassanmaswedish22902 жыл бұрын

    Thank yous

  • @jeffzak6790
    @jeffzak67903 жыл бұрын

    I have made my own turret consisting of a base and a barrel. I moved the pivot on the sprite where I want the barrel to pivot over the base sprite, but when my player is in visual range the barrel sprite noses straight down. It will follow the player but it appears to be off 90 degrees. How would I go about fixing this in your code?

  • @jeffzak6790

    @jeffzak6790

    3 жыл бұрын

    Solved: I created my Barrel sprite in Paint.net and made it horizontal, like it would be sitting in the game. This is wrong. I went back in and flipped the image so the barrel points up in the image. Next, imported it into the unity and then set the custom pivot point in Sprite editor. Then, in unity, just rotated the Z axis to the direction I want towards the player and all is working now.

  • @vannguyencac6644
    @vannguyencac66442 жыл бұрын

    help me, I did the same as the video tutorial but why when the player collides with the bullet, the focus disappears and unity gives an error message

  • @hicumut
    @hicumut2 жыл бұрын

    dude in my case turrets searching for target position when they are not in range. and it causes to error that NullReferenceException how to fix that

  • @spainyoutub
    @spainyoutub2 жыл бұрын

    tengo un problema, la torreta em detecta pero cuando me enfoca no me enfoca linealmente a mi, se me mueve unos cuantos pasos de mas, intento girar la torreta en el eje o girar el punto de vision nada, siempre me enfoca un poco mas arriba de donde esta mi personaje, sabes que puede ser? necesito ayuda graciaaasss

  • @ibrahimizi741
    @ibrahimizi7413 жыл бұрын

    hi man I made a enemy raycast and instanshet but the player damage before the built hit

  • @flickermarc6308
    @flickermarc63082 жыл бұрын

    I'm Having a problem: For some reason My Turret won't work at all. I've Assigned the right collider Tag and have script perfectly fine (I tripled checked) I really need help(For a gamejam)

  • @dmitryovechkin4746
    @dmitryovechkin47462 жыл бұрын

    Turret keeps shooting after leaving borders, what's the problem

  • @sliceggjd
    @sliceggjd2 жыл бұрын

    it dosent look at the player for me any fix?

  • @dragonballz3686
    @dragonballz36862 жыл бұрын

    Bro, I am making a 2d top down space shooter. There is a problem in shooting system, that is , when enemy is shooting and I shoot, then the player's bullet is colliding with enemy bullet and the player's bullet is destroyed but the enemies bullet is not destroyed. Can you tell me what to do to make the both bullets passing away without any collision.

  • @TheGameGuy

    @TheGameGuy

    2 жыл бұрын

    You have to change the layers on both of the bullets and go to project settings>physics2d and down in the collision matrix uncheck the collision box that has the two layers. Like for player bullet put it in player layer and enemy bullet in enemy layer and uncheck player/enemy box in collision matrix

  • @dragonballz3686

    @dragonballz3686

    2 жыл бұрын

    @@TheGameGuy thanks bro. I'm gonna try

  • @joesimmons4235
    @joesimmons42353 жыл бұрын

    How would you make it where the turret cannot move and just shoots in one direction when the player is near? I am trying to add this to my enemy ai script so that it can attack the player

  • @TheGameGuy

    @TheGameGuy

    3 жыл бұрын

    Thats a good question.. and there are many ways i could think of to do this like settting a rotation constraint for the turret but the easiest one would be to just throw in a collider near the turret to block its path of vision so that the line of sight remains pretty much where you want it to be.. like they do with the horses by putting blinders to cover their eyes so that they can only see straight 😂

  • @joesimmons4235

    @joesimmons4235

    3 жыл бұрын

    @@TheGameGuy Lol 😂, thx bro I'll try that!

  • @alekseykustov9574
    @alekseykustov9574 Жыл бұрын

    Tell me it does not return the color to green. That is the code block else { if (Detected == true) { detected = false ; alarmLigth.GetComponent().color = Color.green; Debug.Log("Green"); } } does not work(((

  • @MindGem
    @MindGem2 жыл бұрын

    I mean...how do we get a player to move.....this started in the middle of something...u should start the tutorial from step 1..i didnt see this being a part of a whole?

  • @jeffzak6790
    @jeffzak67904 жыл бұрын

    Question: When I add a 2D Collider to my turret (triangle test sprite) so I can have my player destroy it, the ShootPoint does not fire. When I remove this collider it works as it should. Do you have any ideas on why this is happening and what I can do to fix it ?

  • @cezarfmaciel1107

    @cezarfmaciel1107

    3 жыл бұрын

    Your raycast is probably hitting your own turret collider, then it doesnt work.

  • @shinjonanimations1772

    @shinjonanimations1772

    2 жыл бұрын

    @@cezarfmaciel1107 any fix for when this happens ?

  • @cezarfmaciel1107

    @cezarfmaciel1107

    2 жыл бұрын

    @@shinjonanimations1772 Sorry for the late reply, make a layer for each object (ex: player and the turret), and when going to raycast, use a layermask on it without the player and the turret

  • @shinjonanimations1772
    @shinjonanimations17722 жыл бұрын

    Hey you have any solution for clamping the rotation of the gun ?

  • @sliceggjd

    @sliceggjd

    2 жыл бұрын

    mathf.clamp()

  • @privatethings3789
    @privatethings37892 жыл бұрын

    What would be the code so player would take damage? Please help. I am looking for tutorial like that all over the youtube, i did your turret script, it's great! I subbed from both accounts. But fr, any help with player taking dmg? Please. Awesome video btw!!!

  • @pyxelgamer

    @pyxelgamer

    2 жыл бұрын

    Er, I could give you some stuff for damage... Do you have a github account? I need to add you.

  • @alvyahmed7924
    @alvyahmed79243 жыл бұрын

    The speed of the bullet is not constant... When you get near the turret the speed of the bullet decreases because the value of direction is also decreasing... How can i make the bullet to never lose speed whatever the value of direction??

  • @victormr1601

    @victormr1601

    3 жыл бұрын

    Did you find a workaround?

  • @alvyahmed7924

    @alvyahmed7924

    3 жыл бұрын

    @@victormr1601 Yes, i just had to normalize the direction vector..

  • @spidersense1639
    @spidersense16393 жыл бұрын

    Please make a video on visual studio code intellisense please please bro

  • @mohamadkhawaldeh6264
    @mohamadkhawaldeh62643 жыл бұрын

    my alarm light stays red no matter how far i get any idea on how to fix this?

  • @tejaskutal2922

    @tejaskutal2922

    3 жыл бұрын

    Remove the alarm light completely

  • @Sumdottycoy
    @Sumdottycoy4 жыл бұрын

    Awesome vid

  • @Tuttle321
    @Tuttle3213 жыл бұрын

    Hey, I have the problem that the balls are shooting at the player but the top is not tracking right. How would fix this?

  • @Tuttle321

    @Tuttle321

    3 жыл бұрын

    i fixed it

  • @sliceggjd

    @sliceggjd

    2 жыл бұрын

    @@Tuttle321 HOW

  • @tuthbo1y
    @tuthbo1y3 жыл бұрын

    I am having a problem where my Alarm detects the player when in range but when it leaves the range it still says its detected and wont turn back green. I don't know the logic behind this. Either I typed something in wrong or its something I did or didn't do in Unity it self. Its probably is a simple fix but I would like to hear if anyone has a solution to this. Ill paste my code here and thank you for the tutorial. using System.Collections; using System.Collections.Generic; using UnityEngine; public class TurretScript : MonoBehaviour { public float Range; public Transform Target; public bool Detected = false; public GameObject Alarm; Vector2 Direction; // Update is called once per frame void Update() { Vector2 targetpos = Target.position; Direction = targetpos - (Vector2)transform.position; RaycastHit2D rayInfo = Physics2D.Raycast(transform.position, Direction, Range); if (rayInfo) { if(rayInfo.collider.gameObject.tag == "Player") { if(Detected == false) { Detected = true; Alarm.GetComponent().color = Color.red; } } else { if (Detected == true) { Detected = false; Alarm.GetComponent().color = Color.green; } } } } void OnDrawGizmosSelected() { Gizmos.DrawWireSphere(transform.position, Range); } }

  • @tuthbo1y

    @tuthbo1y

    3 жыл бұрын

    I figured it out but still thanks.

  • @bwoof8242

    @bwoof8242

    3 жыл бұрын

    @@tuthbo1y hey, i have the same problem. how did you fix it?

  • @shinjonanimations1772

    @shinjonanimations1772

    2 жыл бұрын

    @@bwoof8242 You fixed it ? what's the fix ? would really appreciate your help

  • @bwoof8242

    @bwoof8242

    2 жыл бұрын

    @@shinjonanimations1772 i think you replied to the wrong person (^^) im pretty sure i fixed it as well but i don’t remember what i did, sorry

  • @primaldev6666

    @primaldev6666

    2 жыл бұрын

    @@tuthbo1y you still know how to fix?

  • @francinacolley2689
    @francinacolley26894 жыл бұрын

    What do I need to do if I want the player to respawn and restart at the bottom of the screen when shot by a turret bot?

  • @TheGameGuy

    @TheGameGuy

    4 жыл бұрын

    Set players position at the bottom of the screen and when the player gets shot you just need to simply restart the game. void die () { SceneManager.loadScene(SceneManager.getActiveScene ().buildIndex); }

  • @francinacolley2689

    @francinacolley2689

    4 жыл бұрын

    @@TheGameGuy Thank you very much, your content is very helpful for a beginner like myself

  • @mailmike933m

    @mailmike933m

    4 жыл бұрын

    @@TheGameGuy Which script would you put this line of code in?

  • @TheGameGuy

    @TheGameGuy

    4 жыл бұрын

    @@mailmike933m You could simply put it inside your player script or make a gamemanager script that would handle all that stuff like restarting the level, or display gameover panel. things like that.. i would recommend making a gamemanager script to take care of all that..

  • @mailmike933m

    @mailmike933m

    4 жыл бұрын

    @@TheGameGuy Ok, thank you

  • @dontCallMe..
    @dontCallMe.. Жыл бұрын

    the code plz

  • @agungwicaksono6237
    @agungwicaksono62374 жыл бұрын

    I have a problem when deactivate turret, turret continues to be active when once entered the range and no longer deactive, please help me to solve this problem

  • @agungwicaksono6237

    @agungwicaksono6237

    4 жыл бұрын

    i follow your code, but it still not work: using System.Collections; using System.Collections.Generic; using UnityEngine; public class Turret : MonoBehaviour { public float Range; public Transform Target; bool Detected = false; Vector2 Direction; public GameObject Alarm; public GameObject Gun; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { Vector2 targetPos = Target.position; Direction = targetPos - (Vector2)transform.position; RaycastHit2D rayInfo = Physics2D.Raycast(transform.position,Direction,Range); if (rayInfo) { if(rayInfo.collider.gameObject.tag == "Player") { if(Detected == false) { Detected = true; Alarm.GetComponent().color = Color.red; } } else { if (Detected == true) { Detected = false; Alarm.GetComponent().color = Color.green; } } } if(Detected) { Gun.transform.up = Direction; } } private void OnDrawGizmosSelected() { Gizmos.DrawWireSphere(transform.position, Range); } }

  • @TheGameGuy

    @TheGameGuy

    4 жыл бұрын

    How exactly are you de-activating the turret?

  • @agungwicaksono6237

    @agungwicaksono6237

    4 жыл бұрын

    @@TheGameGuy ok, problem solved. I did not put objects to obstruct the player. Thank'u for your tutorial

  • @stefanbartolo

    @stefanbartolo

    3 жыл бұрын

    @@agungwicaksono6237 Can you please explain this as I am not managing to deactivate the Turret and its remaining Red. Thanks

  • @stefanbartolo

    @stefanbartolo

    3 жыл бұрын

    @@TheGameGuy Can you please explain this as I am not managing to deactivate the Turret and its remaining Red. Thanks

  • @bakedpizza4037
    @bakedpizza40372 жыл бұрын

    can you do it for 3d

  • @sliceggjd

    @sliceggjd

    2 жыл бұрын

    Yes

  • @bakedpizza4037

    @bakedpizza4037

    2 жыл бұрын

    @@sliceggjd pls do it

  • @SekyoT
    @SekyoT Жыл бұрын

    It worked for the first few seconds, then the script completely just stopped working and the turret is just there Edit: I Found the problem but unsure how to fix it, when I add a box collider to it it stops working Edit 2: I figured it out, for those experiencing the same problem when adding colliders just add the "Ignore Raycast" Layermask to the turret

  • @vl4do343

    @vl4do343

    6 ай бұрын

    Thank you! You just saved me what could have probably been a week or so of searching. I wish you the best of life!

  • @StickyLabDev
    @StickyLabDev2 жыл бұрын

    btw iam failed ,dang

  • @stormhoundd
    @stormhoundd3 жыл бұрын

    Can you give me discord. I need to something to ask. I have a problem

  • @alekseykustov9574
    @alekseykustov9574 Жыл бұрын

    There is an error in the code, or maybe it was done on purpose ... if (rayInfo) { if (rayInfo.collider.gameObject.tag == "Player") { if (Detected == false) { detected=true; alarmLigth.GetComponent().color = Color.red; Debug.Log("Red"); } } } else { if (Detected == true) { detected=false; alarmLigth.GetComponent().color = Color.green; Debug.Log("Green"); } } here is the correct snippet😆😛

Келесі