Jasper Engine 2D
Time to Customize!!!
So let's make our first custom behavior. How bout we call it "chaseMe" !
var mouseManager = gameCore.getMouseManager();
gameCore.createBehavior("chaseMe",{},{
onUpdate: function(dt){
parent=this.getParentObject();
pos = parent.getPos();
var mousePos = mouseManager.getMousePos();
var dist = Math.sqrt(Math.pow(mousePos[0]-pos[0],2)+Math.pow(mousePos[1]-pos[1],2));
parent.setPosX(parent.getPosX() + ((mousePos[0]-pos[0])/dist*2.0));
parent.setPosY(parent.getPosY() + ((mousePos[1]-pos[1])/dist*2.0));
}
});
Don't freak out! Its not that hard… Now, let me explain the above code.
Custom Behaviors
- First, a custom is behavior is created using the syntax
gameCore.createBehavior( <the name of the behavior>,
<an object with the local variables it needs>,
<an object with the functions that it uses> );
Inside any of the custom behavior function definitions, this.getParentObject() will return the object to which it is attached.
Note: use '*this*' operator to access the functions and variables of the behavior itself, including the ones that were declared in the object above.
-
The new behavior defined has functions that can be overridden:
- onInit
- onUpdate
- onRemove
So we override the onUpdate because the mouse must be tracked during every frame update.
We need to get the mouse coordinates on-demand. Hence we can obtain the MouseManager from the gameCore and can call the getMousePos() on that object.
The following is a simple vector normalisation of the vector between the current object position and the mouse position. (ignore this for now, if you don't get it. Just know that this piece of code simply performs some math that serves to move the object)
var dist = Math.sqrt(Math.pow(mousePos[0]-pos[0],2)+Math.pow(mousePos[1]-pos[1],2));
parent.setPosX(parent.getPosX() + ((mousePos[0]-pos[0])/dist*2.0));
parent.setPosY(parent.getPosY() + ((mousePos[1]-pos[1])/dist*2.0));
- Now the behavior is registered to the gameCore under the name "chaseMe"
Almost There
Now, do you remember we created the objects in the previous page of the tutorial?
THE MAGIC…!!!
All thats left to add is one single line: evilface.addBehavior("chaseMe");
for(i=0;i<10;i++){
for(j=0;j<10;j++){
var evilface = new Jasper.Object("evilface");
evilface.setPos(i*50,j*50);
evilface.addBehavior("sprite").setSprite("../img/evil.png").setHeight(30).setWidth(30);
evilface.addBehavior("chaseMe");
arenaLayer.addObject(evilface);
}
}
Presto!!!
Run the game and run away as the minions chase after you until they eventually hit you or you run out the screen! Thats not fair though… :P