Best viewed in Firefox

Awesty Productions

Basic Artificial Intelligence

November 27th, 2006 by awesty

In this tutorial you will learn how to apply AI (artificial intelligence) to your games so your characters can think for themselves. This is going to be very basic, and not going to involve any trigonometry or anything like alot of AI scripts.
When we are done, we will hopefully have a result like this: Link
Use the arrow keys to move. Notice that the little blue ball follows you. The square tries to chase you when you are in reach (300 pixels) and flashes when it hits you and if you enter the vision of the camera it will set of an alarm (yes, by alarm I mean those dodgy circles…).
We might not get all this done in this tutorial, I might have to make a second, so don’t ask why I didn’t finish it all. ;)

I am using flash 8, but flash MX 2004 will work as well.

First of all, you need to make the character you control, his friend that will follow him, the enemy that chases and attacks/flashes when it hits him and a camera type thing.

The and his friend are simple, each are just one movieclip with one frame (You can do it with a walk cycle etc.). The camera type thing is one movieclip with 2 frames inside it. On the first frame, you need a movieclip of the camera rotating. Make sure you add the field of vision, even if it is transparent. You need it or it won’t work. On the second frame add an MC of the camera setting of an alarm of something
For the enemy, you need two frames as well (a MC with two frames inside it). On the first have you enemy as normal, and on the second have it attacking or something, just as long as it looks different.

On all of those four frames (the 2 from the enemy and the 2 from the camera) add this:

stop();

All does is stop the movieclip from looping.

Now on the man movieclip add this code:

onClipEvent(enterFrame){
    if(Key.isDown(Key.RIGHT)){
        this._x += 5;
    }
    if(Key.isDown(Key.LEFT)){
        this._x -= 5;
    }
}

This makes the MC move left and right. I have explained that is a fair few of my tutorials, so I am not going to explain it here. If you want an explanation try this tutorial.

Give that MC an instance name of ‘man’. It is case sensitive, man is not the same as MAN, Man, mAn, maN, MAn, mAN or any other different ways you can think to type it. ;)

On the enemy, I want you to put this code:

onClipEvent(enterFrame){
    tx = this._x;
    mx = _root.man._x;
    rx = tx - mx;
    if(this.hitTest(_root.man)){
        this.gotoAndStop(2);
    }else{
        if(rx >= 1 && rx<300){
            this._x -= 1;
        }
        if(rx <= -1 && rx>-300){
            this._x += 1;
        }
        this.gotoAndStop(1);
    }
}

Now to explain it. :)

onClipEvent(enterFrame){

All this means is ‘every time the frame is entered, run the following code’.

tx = this._x;
    mx = _root.man._x;
    rx = tx - mx;

This just sets a bunch of variables. The first one is just setting the variable tx to equal the movieclips x coordinate. The second is setting the variable mx to equal the MC ‘man’ coordinates. The third one is setting the variable rx to equal tx minus mx (this MC’s x coordinates take ‘man’ x coordinates.). If tx = 3, and mx = 2, rx = 1 because 3 - 2 = 1.

if(this.hitTest(_root.man)){
    this.gotoAndStop(2);
}else{

This means ‘if this touches the MC ‘man’ (if this.hiTest man), this has to go and stop on frame 2 (The attacking/flashing frame), unless… (else).

if(rx >= 1 && rx<300){
    this._x -= 1;
}
if(rx <= -1 && rx>-300){
    this._x += 1;
}
    this.gotoAndStop(1);
}
}

If rx (tx - mx) is less or equal to 1 (rx <= 1), and (&&) rx is less than 300 (rx<300) this x coordinates decreases by 1. So then it chases the 'man' MC to the left if it is in range.. The next part means the same thing but for the right side.

That is it for this tutorial, because my eyes are starting to hurt from looking at the computer for so long. So stay tuned for Basic AI part 2, which will hopefully be done in the next few days, or when my eyes recover. :P

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blinkbits
  • BlinkList
  • blogmarks
  • del.icio.us
  • digg
  • Furl
  • MyShare
  • NewsVine
  • Netscape
  • Reddit
  • Simpy
  • Slashdot
  • StumbleUpon
  • Technorati
  • YahooMyWeb

RSS feed

82 Comments »

Comment by Bob
2006-11-27 21:54:42

That…was…AWESOME! Thank you so much! Can’t wait till part 2!

On a different note, are you going to do one with triganometry, about A fighting A.I.?

 
Comment by awesty
2006-11-28 07:02:52

You can do a fighting AI without trigonometry. ;)
To tell you the truth, we have only just started doing it at school so I’m not really that good with it. :)

 
Comment by Bob
2006-11-28 08:52:17

That’s good, because I hate trig.

 
Comment by awesty
2006-11-28 15:40:38

Join the club. :P

 
Comment by Bob
2006-11-29 11:52:49

I just got an awesome idea! If I atached the health system backwords (HpBar to my man) to my man, and making my health go down when the enemy flashes/attackes (in my case attacks)That way I have a fighting AI. This is the code I would use. Could you tell me if it would work?:

Enemy:

onClipEvent(enterFrame){
tx = this._x;
mx = _root.man._x;
rx = tx - mx;
if(this.hitTest(_root.man)){
this.gotoAndStop(2);
}else{
if(rx >= 1 && rx-300){
this._x = 1;
}
this.gotoAndStop(1);
}
}

Man:

onClipEvent(enterFrame){
if(this.hitTest(_root.enemy){
_root.hp -= (random(5) 1);
}
}

I would create a health bar for my man and that way it would go down when I was attacked.

 
Comment by awesty
2006-11-29 15:46:10

Yeah, that would work. (btw angle brackets don’t work in comments ;) )

 
Comment by joey
2006-11-29 18:12:56

this is great and i cant wait until part 2 comes out but i would like it to be a bit more advance for my fighting game so have a look and see what you think i need your expert advice ( i added the action script for the AI to it so go to the single player multiplayer works as well if u want to seee it as well lol

this is my game
http://www.deviantart.com/deviation/43628150/

 
Comment by awesty
2006-11-29 19:47:50

What exactly do you want to be more advanced?

You jumping doesn’t work in some places, so fix that. Maybe make the jump a bit quicker, at the moment it takes to long to jump.
Try making sure all the joints on the stick figure connect, at the moment that are broken off. Also maybe add a few more frames to your walk cycle, and his leg grows on the kick.
Give the enemy a walk cycle, and sticks don’t have necks!!!

That seems like a fair bit but once you fix all that your game will be alot more enjoyable. ;)

 
Comment by joey
2006-11-29 20:28:26

the enemy does have a walk cycle but i dont no how to make it walk after me without walking on the spot and where doesnt the jump work?

 
 
Comment by Bob
2006-11-29 22:01:31

Sorry it cut off the rest of my comment. That’s a description to what I will do once this tutorial is done. It’s astronaut 2. Much more sophisticated than #1. Scroll down untill you see a long post by ‘clay inferno’ describing the game.

 
Comment by joey
2006-11-30 08:14:30

oh yer what i ment about more advanced was that i wanted the enemy to turn to face the man and also have a walk cycle and be able to jump lol the jump probably to advanced so yer…….

 
Comment by awesty
2006-11-30 11:06:51

@Bob: Nice idea, now you have to make it. Trust me, the idea is easy, making the game isn’t too hard, but having the patience to finish is the hardest part. I have so many unfinished games, and no complete finished ones yet, so good luck on that. ;)
@Joey: Yep. After I finish part 2 I might make another AI one which will involve walk cycles, facing the right direction and jumping.

 
Comment by joey
2006-11-30 11:12:29

k thx whats part 2 going to be about?

 
Comment by awesty
2006-11-30 11:15:39

It’s going to finish off this tutorial, it is only half done. ;)

 
Comment by joey
2006-11-30 11:17:39

oh ok cool

 
Comment by joey
2006-11-30 11:19:23

by the way i saw on your deviant art account your from australia, me to what state r u in im in QLD

 
Comment by awesty
2006-11-30 11:20:00

Victoria.

 
Comment by joey
2006-11-30 11:22:32

cool i have family down there in melbourne lol
are you really 13? cause ur damn good for a 13yr old

 
Comment by awesty
2006-11-30 11:23:12

14 ;)

 
Comment by joey
2006-11-30 11:33:05

lol well your still damn good for a 14yr old im 15 and i learnt the real basics when i was 13 and last year i wasnt much better. lol my school has bad IT teachers i probably Know more then them lol and you would be like 100 times better.

 
2006-11-30 11:58:27

[…] In this tutorial we will continue from where we left of in my ‘Basic Artificial Intelligence Tutorial’. I recommend you read that tutorial before you continue with this one. In this tutorial we will learn how to make a camera set of an alarm when your character is in its field of vision and how to make something follow your character. […]

 
Comment by sultan
2006-12-12 06:23:20

jhgfd

 
Comment by awesty
2006-12-12 15:49:44

jhgfd to you to.

 
Comment by jesty
2006-12-17 19:39:37

this was helpful but i wanna make a thing liek this only it can go up and down as well so could you help me with the coding for that? its gonna be kinda like merlins revenge and i can nearly get the health and the attacking thanks to you but not the enemy AI and soon i will get having a spawn spot

 
Comment by awesty
2006-12-18 10:58:22

Try this code for the up and down.

if(this._y < (_root.man._y - 25)){
this._y = 3;
}
if(this._y > (_root.man._y 25)){
this._y -= 3;
}
}

Comment by chikonatorr Subscribed to comments via email
2007-12-19 10:34:04

I tried the code you posted above but it gave me the error message saying that it’s waiting for a ) to end the “if(this._y > (_root.man._y 25))” part

 
 
Comment by Bryce K :P
2006-12-21 12:57:09

this is good but, i want my enemy to run, but when i do this and im behind him he runs backwards ._. and i made him have a gun and when im behind him he fires his gun backwards too, can you give me a script so he turns around?

 
Comment by Bryce K :P
2006-12-21 13:00:41

i also can’t kill him when hes walking ._. can you plz help??!?

 
Comment by Bryce K :P
2006-12-21 13:15:58

Also i want him to walk towards me but just enough so his gun’s range hits i don’t want him to get so close that he’s practically on top of me plz help!

 
Comment by Bulletluigi
2006-12-22 06:27:12

ERRRRR it did it again~!!!!
… Bryce K please just send me an e-mail and i’ll reply with the script..

 
Comment by Bulletluigi
2006-12-22 06:29:59

Awesty please delete those last 2 scripts because they didn’t paste correctly.. don’t know whats wrong. It’s ok though I have the correct scripting on my comp and ill send it to you (Bryce K and anyone else that might want it) just send that e-mail to Bulletluigi@hotmail.com

 
Comment by Bryce K :P
2006-12-22 10:26:08

okay ty, but the problem is the enemy comes towards me and just stops attacking if he gets to close (which i don’t want) also when i try to kill him his hp bar goes down but when it reaches zero it goes back to 100 ._.

Keys for my .fla
Left and Right arrow keys (move back and forth)
Up arrow key (jump)
Shift Left and Right arrow keys (sprint)
Ctrl (Primary Lotous if you know what that means its cause you watch Naruto ^_^ if not you’ll just think this is a cool ninja move :P)

Thanks Bullet Luigi!

 
Comment by Bryce K :P
2006-12-22 10:35:06

oh i also have Spacebar (shhots an energy blast :P)

 
Comment by Bulletluigi
2006-12-22 14:33:17

Yes, I watch Naruto =^.^=
I got tired of watching 1 episode a week, so i went to Youtube and watched to episode 175 in japanese w/ english subtitles. It’s much better anyways. Naruto isn’t as annoying.

 
Comment by Bulletluigi
2006-12-22 14:35:40

Umm.. Bryce K are you sure you sent that e-mail? I haven’t got any new mail yet.

 
Comment by Bulletluigi
2006-12-22 16:18:24

When you test your game on your version is your enemy levitating? I am going to do a lot of changing just so you know, but its a pretty cool idea that you have.

 
Comment by Bulletluigi
2006-12-23 13:32:58

Bryce K. i’m not sure of everything that you wanted me to help you with. It’s difficult for me to find my way around in it, so i think you would probably do better asking Awesty. Sorry man I wish i could help more.

 
Comment by awesty
2006-12-23 17:21:21

Yep. Just send it to:

awestyproductions[@]gmail[.]com

 
Comment by Bryce K :P
2006-12-26 11:17:31

its okay man, you tried :P Merry Christmas everyone!

 
Comment by Jake
2006-12-28 05:19:45

Heck yes, gmail is the way to go, mine is sumplesnoob@gmail.com… now I know this sounds noobish (cause I am one…) and I’m only 13, but what would the script for jumping be? …yeah, not even AI jumping… just jumping…

 
Comment by awesty
2006-12-28 18:04:14

Try the platform jumping tutorial.

http://www.awestyproductions.com/tutorials/

 
Comment by Grifo
2007-01-12 06:42:26

OMG I can’t believe Awesty is only 14.

 
Comment by Master MX'er
2007-01-16 09:13:17

Hi ;)

I’m 14 too.
Wow! Finding so many people my age :).

I need help on my game i’m making…
i need a storyline idea-from anyone who
has ideas please :).

I like adventure but what do you all like?

I’m hoping to hear from you…oh by the
way i’ve been doing flash for about 2
years now :).

Signing Off
Master MX’er

————–
My motto –> where there’s a problem there’s
a solution.

 
Comment by awesty
2007-01-16 10:15:13

Heh… Make a game about something you enjoy, so you will enjoy making it. I have been doing flash since the start of last year (2006), but didn’t really start AS until around March or April. So I would like to see what you can do. ;)

 
Comment by Master MX\'er
2007-01-16 18:29:02

Thanks awesty :D

A\’ll i need now is to have a website…:(
It\’s so hard to find a website >_ where there\’s a problem there\’s
a solution

 
Comment by Master MX'er
2007-01-16 18:33:42

Sorry for another post but my message looks
like it got a little messed up
?
:P
Anyway i was going to say I’ll email my game to
you :)

Signing Off
Master MX’er

—–
My motto –> where there’s a problem there’s
a solution

 
Comment by awesty
2007-01-18 11:10:44

I you want somewhere to showcase your work, try:

http://www.deviantart.com/ - DeviantArt
http://www.newgrounds.com/ - NewGrounds

 
2007-01-19 05:33:00

Wha!

This is near enough EXACTLY the same AI tutorial at how2flash.com

One of you are stealing >:

 
Comment by awesty
2007-01-19 14:40:33

lol… no.

The tutorial on howtoflashuses this:
if (Math.sqrt( (rx-tx)*(rx-tx) (ry-ty)*(ry-ty))

That looks a little more advanced than mine.

Also the camera in there tutorial faces the character. The one in mine is just animated, and only goes off if it touches the character.

I don\’t really see how they are EXACTLY the same. Theres uses maths functions like Math.sqrt and Math.atan2, when all mine uses are if statements. Please don\’t acuse me of something that isn\’t true.

 
Comment by Master MX'er Subscribed to comments via email
2007-01-20 06:56:23

Thanks awesty for your response :D

And sorry for not responding earlier…
it’s because of SHCOOL!!!!!!! :(

I am just trying to get a website for
myself.

P.S:
Oh and i have a sort of tute for making
an overview type of game with boundries
,and i have made the code sortof by myself.

Anyway gotta go to sleep now :(

See you!

Signing off
Master MX’er

my motto
—> where there’s a problem there’s
a solution.

 
Comment by awesty
2007-01-20 11:35:15

If you want to make a website, you are going to need hosting.

You can get free hosting from somewhere like:
http://www.freewebs.com/

Or you can get paid hosting.

 
Comment by Master MX'er Subscribed to comments via email
2007-01-20 17:46:36

Thanks Awesty again…

And i’ll tell you asap when i get a website

Signing off
Master MX’er

my motto
—>where there’s a problem there’s
a solution.

 
Comment by Master MX'er Subscribed to comments via email
2007-01-21 16:58:40

Hi Awesty.

Got my site:D…
you can find it at:
http://www.freewebs.com/mastermxer/

But right now it’s under construction so
there is’nt much at all:(

Anyways.

Signing Off
MasterMX’er

my motto
—>where there’s a problem there’s
a solution.

 
Comment by awesty
2007-01-21 20:04:12

Nice. ;)

 
Comment by Robert F.
2007-01-22 07:43:31

when i touch the item it just disapeers and the smallitem doesnt show up

 
Comment by Master MX'er Subscribed to comments via email
2007-01-22 23:25:21

ummm…

i have a tute for making a person jump

i could give it to you awesty…
if you want.

 
Comment by Master MX'er Subscribed to comments via email
2007-01-24 00:22:34

Hey awesty you can look at one of my games on my
site.I have just loaded it on:D

I will be loading others on soon enough.

Signing off
Master MX’er

my motto
—>where there’s a problem there’s
a solution.

 
Comment by bob
2007-01-25 12:16:25

Dude that was awesome i cant wait till 2

 
Comment by awesty
2007-01-26 11:54:43

Part 2 is out.

 
Comment by Master MX'er Subscribed to comments via email
2007-01-28 06:06:33

Hi sorry i havent been here for
a while i was just contemplating.

Nice to be back.
Hello and welcome back awesty!!

Good to see you again:)

anyway
Signing Off

Master MX’er

 
Comment by MasterMX'er Subscribed to comments via email
2007-02-25 05:15:35

ok i finally got my site to look proffesional so please feel free to drop by…that includes you awesty…and i hope you dont mind me putting up my link to my site.
well anyway here it is..enjoy
http://www.freewebs.com/mastermxer/index.htm

Siging off
MasterMX’er

 
Comment by awesty
2007-02-25 12:56:44

Nice site ;)

 
Comment by jesse
2007-02-26 13:18:14

just wondering do you have any source codes because im i beginer at flash and haveing troubles animating the camera im trying to motion tween it but for some rease i want the camera to rotate but it goes across the screen i know thats sad that i cant animate it but ya if you could help me in any way that would be soo helpful ^_^

 
Comment by jesse
2007-02-26 13:25:33

nvrm lol i figured it out lol i feel like a noob lol

 
Comment by MasterMX'er Subscribed to comments via email
2007-03-21 07:58:17

Haven’t dropped by in a while…well done in finding what you needed to jesse…dont feel like a noob, everyone started out not knowing what they were doing. My advice is to seek advice from those with knowledge such as awesty or fool around and fins things out for yourself….as for myself i was self tought…pretty stupid idea.

Just to rate this rockin tute…too good for a rating, helped me alot…thnx :D

 
Comment by awesty
2007-03-21 18:36:02

Thanks man.

Sorry I havent written any tutorials for ages guys but I have been doing alot off stuff from changing the servers and getting used to a heap of new programs I have gotten ^___^

 
Comment by Shawn
2007-04-09 07:56:16

// I’m making such an…

addProperty(sarcasm){
interesting
}

/* …game, Where is your HitTest tutorial? I cant seem to find it… (I need to check something… ) */

 
Comment by Shawn
2007-04-09 08:04:18

nevermind. I found the search bar. ;)

 
Comment by awesty
2007-04-09 12:04:38

If you click on the ‘Tutorials’ link up the top it will take you to a page that lists all of the tutorials on this site.

 
Comment by Trunk Monkey
2007-06-06 08:21:34

How do you make the enemy move up and down?

 
Comment by i wish i was awesty Subscribed to comments via email
2007-06-21 06:39:42

i have no balls

Comment by SaroVati Subscribed to comments via email
2007-06-25 07:37:18

Don’t b immitating awesty now…. sigh, really sad lol. Btw Trunk, if u wanna do it with AI, heres the code u put on enemy i think:

if(this._y (_root.man._y 25)){
this._y -= 3;
}
}

hasn’t been tested out by me yet but it might work lol =)

 
 
Comment by Light (MasterMX'er Subscribed to comments via email
2007-06-28 07:13:52

Greetings.
Oh and for the moving up and down, i’m afraid you’d be waisting time asking me lol…i’d have to dig up some pretty old archives just to find it, plus I see someone already covered it.
Well just wanted to come back and check on things. Like the site!!…lookin pretty damn good.

That’s all.

-Light-

p.s.
Once again, Big Ups for all your tutorials…they’re deff a big help for me.

 
Comment by ISQ Subscribed to comments via email
2007-08-23 02:03:51

great tutorial awesty! Really enjoyed it. but for those of you who were wondering how to get the enemy to chase you every were, here is a code that works.

onClipEvent(enterFrame){
ty = this._y;
my = _root.man._y;
ry = ty - my;
if(this.hitTest(_root.man)){
this.gotoAndStop(2);
}else{
if(ry >= 1 && ry-300){
this._y += 6;
}
this.gotoAndStop(1);
}
}
onClipEvent(enterFrame){
tx = this._x;
mx = _root.man._x;
rx = tx - mx;
if(this.hitTest(_root.man)){
this.gotoAndStop(2);
}else{
if(rx >= 1 && rx-300){
this._x += 6;
}
this.gotoAndStop(1);
}
}

 
Comment by hiutopor Subscribed to comments via email
2007-09-18 00:18:55

Hi

Very interesting information! Thanks!

Bye

 
Comment by ike Subscribed to comments via email
2008-04-27 04:49:09

how to make the enemy turn around if you go past him, not just walk backwards?

 
Comment by BO-dum
2008-09-05 02:11:18

how do i make the baddie go up and down aswell

 
Comment by reece Subscribed to comments via email
2009-03-10 18:11:33

i can make my enemy move up to follow using this code
onClipEvent(enterFrame){
ty = this._y;
mx = _root.man._y;
ry = ty - mx;
if(this.hitTest(_root.man)){
_root.hp -= (random(5)+1);
}else{
if(ry >= 1 && ry<300){
this._y -= 1;
}
if(ry -300){
this._x += 1;
}
this.gotoAndStop(1);
}
}
but i cant figure out how to reverse it so he moves down with the enemy

 
Comment by Tweety Subscribed to comments via email
2009-03-11 04:51:56

Hi all…I’m making a game and i have problem. I will explain it on this tutorial. I want to enemy follow character only if camera see him. I was experimenting for hours and i didnt find a way to do it. Help me please. Thank you :)

 
Comment by Isaac Subscribed to comments via email
2009-04-06 08:03:22

how do u make an enemy turn around if u go past him, not just backwards

Comment by Tweety Subscribed to comments via email
2009-05-30 19:58:09

do it with _xscale….. this is a little different code but i think it will help you:
onClipEvent (load) {
var scale:Number = _xscale;
var speed:Number = 10;
}
onClipEvent (enterFrame) {
if (this.hitTest(_root.hrac)) {
this.gotoAndStop(4);
} else {
if (rx>=50 && rx<350) {
this.gotoAndStop(1);
this._x -= speed;
_xscale = -scale;
}
if (rx< =-50 && rx>-350){
this.gotoAndStop(1);
this._x = speed;
_xscale = scale;
}
}
}

 
 
Name (required)
E-mail (required - never shown publicly)
URI
Subscribe to comments via email
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> in your comment.