Login | Register

Loops

September 6, 2006, 09:14 by Calle
[loading]
-->
<b>Question:</b> "Well for starters I am attepting to make an rts, and I have most of the engine done (unit selection,resource gathering, attacking, simple AI). However, I need to know how to display all of the contents of an array. I have an array for my town center building that stores all the unit creation/upgrades (It's an AoK clone), and their respective symbols/icons. Wat I need to know is how to draw all the icons and assign them a collision rectangle without saying:

draw_sprite(array[0,spr],-1,x,y)
draw_sprite(array[1,spr],-1,x,y)
draw_sprite(array[2,spr],-1,x,y)
draw_sprite(array[3,spr],-1,x,y)
draw_sprite(array[4,spr],-1,x,y)


etc...


And then I need them to have a collision rectangle because I need them to be clickable. Any help would be appreciated"

<b>Answer:</b> This is a typical task for a loop. Any loop would do, but I'll use for. First of all you need to determine how many times you need to run draw_sprite, that is, how many sprites that needs to be drawn. You didn't say what that value is based upon, but I assume it might not always be the same, thus I use a variable which I call nr_of_sprites. Assign it anyway you like, maybe by using the object count function, if it is based upon the numbers of units e.g.

Now do it like this:
for (i=0; i<nr_of_sprites; i+=1) {
draw_sprite(array[i,spr],-1,x,y);
}


The only problem I see with this, is that the x and y positions seems to be constant. I assume you don't actually want that? Say you are creating a list, then you might want to have a space with five between each item, and you know the height of each item is 10, so you say: draw_sprite(array[i,spr],-1,x,y+15*i); and your code will be dynamic when creating the list. All will get different height.

To use a imaginative rectangle for collision you must have a structure though, as the one I suggested with i*15. If it doesn't have a structure, you won't be able to calculate which item was pressed, but if you have a structure, you could. Here is how:

item = (mouse_y-y)/15

Item now store a value, 1, 2 or 3 etc, and it's refering to the same button as array[item,spr].

But don't use the function collision_rectangle. Just create an expression that says something like this:
if (mouse_y<15*nr_of_sprites) && (mouse_y>y) {

Then the same thing for x of course. I hope this helped.

Comments

Loading comments... [loading]
.
Users logged in:

game maker articles, game maker examples, game maker tutorials, gmtutorials, game maker questions and answers, game maker crash course, how to create games