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
i looked so long for an tutorial like this thanksss
fast and simple to understand and to the point! Thank You !
This helped so much, thank you for your expertise!
Thanks dude for awesome tutorials. 👌👌
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
2 жыл бұрын
i still failed
Great tutorial. Thanks!
Really good tutorial! Thank you. Worked perfectly.
@StickyLabDev
2 жыл бұрын
doesnot work now 2019
@sliceggjd
2 жыл бұрын
@@StickyLabDev it does
ive been trying to do this for months thanks
Thanks u broo, i love the video
Realy good. thanks.
thanks man
thank you so much
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
2 жыл бұрын
dang ,thanks
@warmasterkyst7518
Жыл бұрын
Bro thx u
@dontCallMe..
Жыл бұрын
u save 14 minutes from my life thx
Thanks
Do u mind if i can have the complete project and assets or just the turret bot?
Thank yous
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
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.
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
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
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
hi man I made a enemy raycast and instanshet but the player damage before the built hit
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)
Turret keeps shooting after leaving borders, what's the problem
it dosent look at the player for me any fix?
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
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
2 жыл бұрын
@@TheGameGuy thanks bro. I'm gonna try
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
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
3 жыл бұрын
@@TheGameGuy Lol 😂, thx bro I'll try that!
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(((
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?
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
3 жыл бұрын
Your raycast is probably hitting your own turret collider, then it doesnt work.
@shinjonanimations1772
2 жыл бұрын
@@cezarfmaciel1107 any fix for when this happens ?
@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
Hey you have any solution for clamping the rotation of the gun ?
@sliceggjd
2 жыл бұрын
mathf.clamp()
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
2 жыл бұрын
Er, I could give you some stuff for damage... Do you have a github account? I need to add you.
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
3 жыл бұрын
Did you find a workaround?
@alvyahmed7924
3 жыл бұрын
@@victormr1601 Yes, i just had to normalize the direction vector..
Please make a video on visual studio code intellisense please please bro
my alarm light stays red no matter how far i get any idea on how to fix this?
@tejaskutal2922
3 жыл бұрын
Remove the alarm light completely
Awesome vid
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
3 жыл бұрын
i fixed it
@sliceggjd
2 жыл бұрын
@@Tuttle321 HOW
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
3 жыл бұрын
I figured it out but still thanks.
@bwoof8242
3 жыл бұрын
@@tuthbo1y hey, i have the same problem. how did you fix it?
@shinjonanimations1772
2 жыл бұрын
@@bwoof8242 You fixed it ? what's the fix ? would really appreciate your help
@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
2 жыл бұрын
@@tuthbo1y you still know how to fix?
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
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
4 жыл бұрын
@@TheGameGuy Thank you very much, your content is very helpful for a beginner like myself
@mailmike933m
4 жыл бұрын
@@TheGameGuy Which script would you put this line of code in?
@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
4 жыл бұрын
@@TheGameGuy Ok, thank you
the code plz
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
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
4 жыл бұрын
How exactly are you de-activating the turret?
@agungwicaksono6237
4 жыл бұрын
@@TheGameGuy ok, problem solved. I did not put objects to obstruct the player. Thank'u for your tutorial
@stefanbartolo
3 жыл бұрын
@@agungwicaksono6237 Can you please explain this as I am not managing to deactivate the Turret and its remaining Red. Thanks
@stefanbartolo
3 жыл бұрын
@@TheGameGuy Can you please explain this as I am not managing to deactivate the Turret and its remaining Red. Thanks
can you do it for 3d
@sliceggjd
2 жыл бұрын
Yes
@bakedpizza4037
2 жыл бұрын
@@sliceggjd pls do it
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
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!
btw iam failed ,dang
Can you give me discord. I need to something to ask. I have a problem
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😆😛