ForumsProgramming ForumCode Needed

14 4578
mikecranbo
offline
mikecranbo
45 posts
Nomad

OK so I'm a robot game and i want the robot to shoot whats the code?or how can I do it?

  • 14 Replies
RSKS
offline
RSKS
7 posts
Peasant

its called hitTest function
try this tutorial [url=http://asgamer.com/2009/as3-flash-games-for-beginners-registering-hit-tests]

gaboloth
offline
gaboloth
1,612 posts
Peasant

what? hitTest to make a robot shoot?
do you mean shooting or make the bullets hurt enemies?

mikecranbo
offline
mikecranbo
45 posts
Nomad

yes.

P051D3N
offline
P051D3N
25 posts
Nomad

He wasn't asking a yes or no question. He means, do you wan't to know:
1. How to make a robot fire a bullet.
2. How to make the bullet hurt enemys.
He was asking which you were trying to do.

mikecranbo
offline
mikecranbo
45 posts
Nomad

1. How to make a robot fire a bullet.

beech
offline
beech
107 posts
Nomad

first, we really have no way of knowing what kinds of tools you're using, what language you're programming with, or several other parameters one needs to consider when building a game. but i'll assume your using Flash and AS3, both of which are the tools of the trade. yes, one can still program in AS2, but AS3 is the most current language version and if you haven't started learning yet - learn AS3 - even it will be updated sometime soon.

if you haven't considered/discovered this already, you will have to write some code in order to achieve you goals here. although you 'can' use some tools that are out there (like gamemaker) but you will not succeed even with that if you don't learn the syntax of their system.

ok, let's see if i can sum this up

so - first you need two mc or sprites, one robot, one bullet.

next - you'll need to have a 'trigger' to shoot, right - so you'll need to set up a keyboard or mouse event *listener*. listeners are an important part of making game UI (user interface) these are the triggers that tell us the user is doing something, and we must respond to that input.

let's assume the robot is placed on the stage, just standing there for now, doin nothin - we want to simply make him shoot. so we need our trigger/listener - so let's use the mouse for now (simpler), so we need to write some code, make a new layer above the robot's layer in the main timeline, title it 'actions', select the first keyframe and open the 'actions' panel (or use F9) - this is where you write code - we need to create a basic listener for a mouse event, that event then is 'handled' by a method we will define - here's the line:

addEventListener( MouseEvent.CLICK, shoot );

function shoot( e:MouseEvent ):void {
//our code to shoot will go here
}

the first line 'adds' the listener for a mouse event to the main timeline or 'stage' - the second thingy there is a 'method' - this will be triggered or 'handled' by the mouse event - you can see we've targeted this method in the listener (ie. shoot)

now we have a few things to do in the method in order to get the robot to fire the bullet - we need to make an instance of the bullet and that bullet has to either 'know' or be 'told to' travel in the direction it was fired. to create a bullet out of thin air, we need to 'instantiate' an instance of the Library Class - we do this by using a 'linkage id' - so let's do that: you've drawn a bullet, and converted it to a symbol, let's say MC (movieclip) (aside: easy people, keepin this basic) - so, in the properties panel of the MC (right click the symbol in the Library) give it a linkage id - say, "Bullet" (that's original...lol) now we can 'link' to the symbol by using the id in our code - so back to the code - in the method shoot(), we'll start off by building the bullet instance like so:

var b:MovieClip = new Bullet(); //"Bullet" is the linkage id

now we need to tell the bullet where to be, well, we want it to come from the robot, right, so we'll use the robots coordinates as our basis, then add a little to position it wherever the 'gun' will be - but that will be up to you since i don't know those things - for now i will use arbitrary increments, assuming the registration point of the robot is at center, and he's around 40, 40, let say, +20x and +0y (center y, right x) and we'll fire to the right - so let's add that to the code:

b.x = robot.x + 20;
b.y = robot.y;

now that we have 1) made the bullet, 2) told it where to be - now we have to add it to the DisplayList so we can see it:

addChild( b );

ok - doing good so far - now the next thing is making the bullet move. so on every frame (or any increment) we want to adjust the position of the bullet, in our case right now, to the right. how fast? well depends on what your doing, so let's just say about 20 pixles per frame - that's pretty fast. however we still need a mechanism to do that on every frame - couple of ways to go here (in fact there are several ways/methods to do this overall) - 1) could create a frame event on the instance, or 2) use a single frame event and iterate over any/many instance - the latter is more popular and more efficient by most standards. but i'm not going to go into the complications of iterating an array, that is more advanced - let's just give the bullet an event listener that will make it move and 'assign' it to the instance for now. so we need to target the instance with the listener, and create a method to process the motion, so back in our shoot() method we'd add:

b.addEventListener( Event.ENTER_FRAME, move );

and we'll create another method like this, that is the handler for the event:

function move( e:Event ):void {
e.currentTarget.x += 20;
}

you'll notice "e.currentTarget" - ? what the heck is that? well 'currentTarget' is a 'roperty' of the Event class that tells us what the event is in reference to - in other words, the bullet - but more specifically *that* particular bullet instance (there's more to it but marching on...)

but we also need to think about something else here - what happens when the bullet leaves the stage? (let alone hits something) we need to add a check to see if it's not needed anymore - if/when, we'll want to remove it, or else our whole program will get bogged down after we've shot a few hundred bullets and they're all still traveling off into lala land and processing their events... forever... - so we add a 'condition' and check for the 'end' of the stage:

if( e.currentTarget.x > stage.stageWidth ){
e.currentTarget.removeEventListener( Event.ENTER_FRAME, move );
removeChild( MovieClip(e.currentTarget) );
}

also note that we'll need to 'remove' the event listener so that it doesn't continue running (although we can get away with loose referenced listeners and the GC will get rid of it if there are no remaining instance refs - but it's best practice to remove it explicitly)

now, with those things in place we should be able to make the robot fire a bullet - so all together our code looks like this:

addEventListener( MouseEvent.CLICK, shoot );

function shoot( e:MouseEvent ):void {
var b:MovieClip = new Bullet();
b.x = robot.x + 20;
b.y = robot.y;
b.addEventListener( Event.ENTER_FRAME, move );
addChild( b );
}

function move( e:Event ):void {
e.currentTarget.x += 20;

if( e.currentTarget.x > stage.stageWidth ){
e.currentTarget.removeEventListener( Event.ENTER_FRAME, move );
removeChild( MovieClip(e.currentTarget) );
}
}


so this is very, VERY basic, our robot does nothing but stand in one place and when you click the mouse shoot a bullet to the right - that's all - there's a ton more to do to make it into a game, robot movement, bullets hitting things, enemies, scoring, effects, UI screens, etc. - much to do

so this probably doesn't make a whole lot of sense to you, i'm guessing, since many of the basic principles here are not being explained, but what it should tell you is that there is a lot of work to making games, and we haven't even begun to scratch the surface here. my suggestion is to start at the beginning, and read, do some more reading, then read some more - start with devouring the Flash 'getting started' section of the Help docs and then hit the thousands of Tutorials out there, and try some things, experiment and learn.

gaboloth
offline
gaboloth
1,612 posts
Peasant

Hey, good work man! Awesome little tutorial!
If you haven't understood much this, you should read the awesome tutorial of Michael James Williams.in the extras he add bullets too.
I don't remember the URL but just google the name.
Oh, and if you want to aim with mouse you should do something like this

var direction:Number = Math.atan2( startingXDirection, startingYDirection );
xDirection = Math.cos( direction );
yDirection = Math.sin( direction );
rotation = ( 180 / Math.PI ) * direction + 90;

In the constructor function.

beech
offline
beech
107 posts
Nomad

thanks gaboloth :P i really skipped over some things though - lol

one quick optimization for a mouse aim system would be to use something a bit more like this:

var d:Number = Math.atan2( robot.x-mouseX, robot.y-mouseY );
robot.rotation = d * (180/Math.PI);

-----
also let me clarify that a 'constructor' is a special method that is written within a Class file - and although you can place code, pass arguments, etc within a constructor - it will not be used to iterate a loop like enterframe, which is where you'd want to place the aiming code so that it updates on every iteration. the above code is for a basic timeline implementation, i didn't even wanna touch writing classes here (although i rarely use timeline coding anymore)

Darkroot
offline
Darkroot
2,763 posts
Peasant

You gotta love atan2 for anything mouse orientation related. But yeah I don't see any classes therefore there is no constructors. Personally I would use classes for something big like a robot shooting game but the code you wrote above is pretty decent for shooting.

Thought I wouldn't encourage giving people entire sections of code that they are most likely just to copy and paste into their game without learning anything.

beech
offline
beech
107 posts
Nomad

yeah Darkroot - i rarely code on the timeline, but this was a basic example with just a little information - and yes, that is why i wrote and stepped through the explanation, hopefully he'll pick up something from it - but... from further thread reading (after lol) in some other posts it seems that he may not really be interested in learning after all, but rather passing off others work as his own. i didn't even want to get into arrays here LOL, let alone the concept of Class structure.

also - yepper atan2, very handy - but lately i've been working mostly with vectors (actual math vectors and not the Vector class) - really fast math operations - rather than running through calculations using trig (although there is always a place for it, sometimes the only way, and some internal method of most vector classes do use trig methods of course)

Darkroot
offline
Darkroot
2,763 posts
Peasant

Yeah it's a shame we need more experienced and eager learners in the forum.

Array's are not complicated and classes aren't either really, maybe a little complicated.

Can you expand on what you've been doing with vectors I'm highly interested in more efficient options.

beech
offline
beech
107 posts
Nomad

right on - yeah arrays are really simply a list, but there is a great deal of power there, and Classes aren't rocket science either, but they can become a complex subject, especially when getting into deep and more proper OOP princples, Singletons, interfaces, design patterns, etc.

vectors - well a vector is really nothing more than a point in space with at least 2 dimensions (x,y) - by definition of it's location, you also 'know' the hypotenuse, or rather in vector terms, it's magnitude. so by the mere act of defining the location we can get tons of information about the right angle within the cartesian plane. but even better, you can perform operations on vectors - like add one to another, subtract, multiply, divide, get a dot product, etc - these operations resolve (mostly) to simple arithmetic, which is performed very, very fast in Flash.

say, for instance, a typical problem might be to find the angle between the player, and another object, we might use atan2 right - with similar syntax to what i previously wrote - so you can do the same thing by subtracting the object vector from the player vector, resulting in a x1-x2, y1-y2 operation, simple math=fast - so we get a third vector in return, one with the origin at the player, pointing at the object - we can then get the hypotenuse using pythagoras (called internally in a given vector class usually as a getter for the 'angle' property) - this is faster than performing a trig operation.

another one is moving an object - we usually do so by incrementing x,y right - now if we're moving on some angle, we'd usually have to figure out the angle using its rotation (or something) and then derive the proper increments for x,y by using sin,cos then multiply those values by the velocity in order to get the correct 'new' position of the object - BUT using vectors you simple store a reference vector for the objects velocity by length of its magnitude, rotate it to the angle of travel, and add it to the object's vector and bam, done - instant new position - way faster, far less complicated.

but more than the speed, i'm digging the ease of use - once you get the concept, it very easy to plot courses, add several vectors together, find positions, estimate a future position, or to do things like get an average from a series of angles (can you envision the code block it would take to do that with trig methods - although, of course, possible)

another handy one is to 'normalize' a given vector - and use that as a relational unit, by doing so you can easily extend a 'line' on the vector to any distance by simple multiplication of the normalized magnitude value, which by the way, resolves to the trig function values of the vectors angle for x and y ... pretty cool huh

they just plain make life easier :P

Darkroot
offline
Darkroot
2,763 posts
Peasant

Well you didn't really have to explain it in that much detail I know basic actionscript and have done calc 1. But the 'normalize' vector is interesting. The only thing that bothers me in flash which the geometry is how 0,0 is on the on the top of the screen and the angles are different from normal.

OOP princples, Singletons, interfaces, design patterns, etc.


I don't have a book that covers that yet could you give me a brief summary or even a link to a good book that covers those aspects of OOP?
beech
offline
beech
107 posts
Nomad

LOL - cool - but if anyone ease is reading the thread they may gain something from it too

yeah - that is always an odd issue that TL is 0,0 and y is inverted - but fortunately, our mechanisms in programming for use/calculating those angles is also based in this system (in a manner of speaking) where 0 is based in a right-hand direction, negative angles rotate CCW, and positive angle are CW - so it all works out

OOP is a pretty broad subject, there is a lot of information out there, discussion and conjecture - some believe that although AS has improved and taken a more OOP approach, it is still not truly a OOP system. i can't think of anything specific, but you can find all kinds of discussion online of course. i do have a friend who co-wrote several books on AS and has been a beta tester for Adobe and is a great teacher in general: [url=http://www.quip.net/blog/]
but i'm not certain that those speak about OOP specifically, although i'm sure it is considered.

Showing 1-14 of 14