Posts Tagged ‘ game making ’

How to make Object Instancing

First of all, this tutorial is written based on revision 1.0.3 so if you don’t have it, download it from here.

To have instances of an object, you need to make a class for it.

Its simple and flexible.

function Object ()
{
this.id=0;
this.x=0;
this.y=0;
this.direction=0;
this.speed=0;
this.life=0;
this.draw = function ()
{
draw_sprite(this.id,this.x,this.y,this.life*3);
}
}

This is an example of a class named Object with some parameters and a function for drawing the object.
Project settings are not anything special, simply put:

function Project_Settings (id)
{
set_title(“Object Instancing”);
set_screen(800,600);
}

And then define an Array and a variable:

var rocks=new Array();
var can_create;

rocks is gonna be an array of Object. but how ?

In Start event put :

for (var i=0;i<20;i+=1)
{
rocks[i]=new Object();
rocks[i].id=load_texture(“gem_”+Math.floor(Math.random()*5)+”.png”);
}

We want to have 20 instances of Object class, with random textures loaded from Sprites folder with names like “gem_1.png”

Then, initialize our only variable:

can_create=true;

In this example we want to make 20 gems at mouse clicking point and having the gems moving in different angles.

So before doing anything, write onMouseButtonPressed event:

function onMouseButtonPressed (e)
{
if (can_create)
{
can_create=false;
for (var i=0;i<20;i+=1)
{
rocks[i].x=e.X;
rocks[i].y=e.Y;
rocks[i].life=80;
rocks[i].direction=Math.floor(Math.random()*360);
rocks[i].speed=Math.floor(Math.random()*3)+3;
rotate(rocks[i].id,rocks[i].direction);
}
}
}

can_create is just a variable that controls when we can create our instances.

We have a loop that fills every single object in rocks array with position of mouse clicked point, a life, random direction and random speed and finally a rotation to object’s angles.

Now the Main event:

function Main (id)
{
if (!can_create)
{
for (var i=0;i<20;i+=1)
{
if (rocks[i].life>0)
{
rocks[i].life-=1;
rocks[i].draw();
}else{
can_create=true;
}
rocks[i].x+=xval_to_direction(rocks[i].id,rocks[i].direction,rocks[i].speed);
rocks[i].y+=yval_to_direction(rocks[i].id,rocks[i].direction,rocks[i].speed);
}
}
}

We draw every single object while its life is larger than 0. once its not, we can create another bunch of objects.

And using the functions xval_to_direction and yval_to_direction we move every object along its direction.

Note: objects will fadeout by the time they loose life.

%d bloggers like this: