Manipulate player position

1,123 views
Skip to first unread message

Finn G.

unread,
Jun 7, 2012, 8:56:24 AM6/7/12
to melonJS - A lightweight HTML5 game engine
Hello!

First, sorry for my bad english, but english is not my main language.
----------

Im currently developing a "Pokemon-like" MMO-Game and im stucking at
multiple maps.

Look at my image: http://www.abload.de/img/mapexamplet0jpe.png
I hope, i'll explain everything. If I go in 4, I'll be teleported to 2
instead 3 because its setted like this in the tmx file.

It would be very nice if you help me! :)

Regards,
Finn

Finn G.

unread,
Jun 7, 2012, 8:58:46 AM6/7/12
to melonJS - A lightweight HTML5 game engine
I could solve the problem if I could manipulate the player position,
for example me.pos.x = 10 will set the player to position 10.

melonJS

unread,
Jun 7, 2012, 11:16:32 PM6/7/12
to mel...@googlegroups.com

you can manipulate player position :)

what you need to do is to store in an array is a list of exit for each map.
when loading the map, just check if an exit door is defined, in that case you can update the player position 
( in that case it would take place in the player init function, and would require to change the entity pos property).

another alternative would be to use an invisible object in the map, that would be use to update here mentioned array (on the onDestroy function), and to check systematically for that object after you switched to the new level as well.
it's maybe a bit more complicated to achieve.

finally here is bunch of useful stuff, depending on how you choose to implement this :

keep in mind that the inheritance tree for entity in melonjs is :
-> me.Rect -> me.SpriteObject -> me.ObjectEntity

Ravetracer

unread,
Jun 8, 2012, 1:34:11 PM6/8/12
to mel...@googlegroups.com
Hi there, 

I'm doing the same thing and just solved it, as Olivier proposed.

Here is my solution:

I've got an init.js with an object with spawn points for each map:

Example: 
The key is the ID of the current map, in this object the key is the map, where I come from and the spawn points taken from Tiled (and later multiplied with the tile size)
var spawnPoints = {
    'woods_01' : {
        'church'                : { x : 36, y : 2 },
        'woods_03'              : { x : 51, y : 96 }
    }
}

On every level load, I set a gamestat variable "last_map" (I know, gamestat is for score etc. but it can be used for everything ;-) ) with the current level ID, so I can positon the player then like this (player entity init function):

        if( spawnPoints[ me.levelDirector.getCurrentLevelId() ] &&
            spawnPoints[ me.levelDirector.getCurrentLevelId() ][ me.gamestat.getItemValue('lastmap') ] ) {
            this.pos.x = spawnPoints[ me.levelDirector.getCurrentLevelId() ][ me.gamestat.getItemValue('lastmap') ].x * tileWidth;
            this.pos.y = spawnPoints[ me.levelDirector.getCurrentLevelId() ][ me.gamestat.getItemValue('lastmap') ].y * tileHeight;
        }

In Tiled you only have to define me.levelEntity objects with their corresponding attributes like "to", "duration" and "fade"...
It works in my game like a charm.

The disadvantage is, that you have to define for each map the spawn points in the init file and where you come from, but it depends on the num of maps and exits per map how big the SpawnPoint object would be ;-).

melonJS

unread,
Jun 13, 2012, 12:54:30 AM6/13/12
to mel...@googlegroups.com

Great answer :)

About the mentioned disadvantage, that's why I was proposing a specific Spawn object that you can place in your map and use the getEntityByName to find it and corresponding position (might give a better generic approach to it, thought a specific object still needs to be defined in each maps).

Also, as you might know, each object have a unique GUID per level, so you can also store any specific value in an other table (or using gamestat), like if you already went through it (in that case you use the specific spawn point, or else you use the default one).

melonJS

unread,
Jun 13, 2012, 12:57:13 AM6/13/12
to mel...@googlegroups.com

One last comment :

it's also possible to specific "executable code" from Tiled (was descrbied/used by Norb in a previous post/example).

Add a property in Tiled ("function" for example) with the value (still in tiled) containing the code to execute, and from within your init function you can do an assert(this.function) to execute it. THis is also a powerfull and generic way to add any specific behavior in a generic way !

Ravetracer

unread,
Jun 17, 2012, 5:46:40 AM6/17/12
to mel...@googlegroups.com
Just a short comeback of this thread ;-).
I've done it now through the proposed SpawnObject. 
It comes with some advantages:

1. saved many lines of code 
2. spawn points are visible for the map designer
3. it's dynamic, what else to say :-)

So here's my current and good working solution:

Object in Tiled called "SpawnPoint" with the attribute "fromMap" which describes, from which map the player has to come to get spawned to this point.
The number of spawn points is nearby unlimited, I think.

Further I've got a method "mapSettings" in "jsApp" which is fired through "me.game.onLevelLoaded = this.mapSettings.bind(this);"

In this method, I'm going through current spawn points and set the player position to the corresponding one (fyi: I'm using jQuery for some other things, here for traversing):

        /**
         * Evaluate spawn points and set player to the corresponding position
         *
         * @type {*}
         */
        var spawnPoints = me.game.getEntityByName('SpawnPoint');
        var player = me.game.getEntityByName('mainPlayer');
        $.each( spawnPoints, function( index, obj ) {
            if( obj.fromMap == me.gamestat.getItemValue('lastmap') ) {
                player[0].pos.x = obj.pos.x;
                player[0].pos.y = obj.pos.y;
            }
        });

        me.gamestat.setValue( 'lastmap', me.levelDirector.getCurrentLevelId() ); 

IMHO this is a good and solid solution for top-down RPGs and map switching. 
What do you think?

Rafael Almeida

unread,
Sep 5, 2012, 9:12:48 AM9/5/12
to mel...@googlegroups.com
i try this solution but got error  cannot instance entity of type 'spawnpoint': Class not found! for each spawnpoint created my code:

var jsApp
{
/* ---
Initialize the jsApp
--- */
onload: function()
{
// init the video
if (!me.video.init('jsapp', 640, 480, false, 1.0))
{
alert("Sorry but your browser does not support html 5 canvas.");
         return;
}
// initialize the "audio"
me.audio.init("mp3,ogg");
// set all resources to be loaded
me.loader.onload = this.loaded.bind(this);
// set all resources to be loaded
me.loader.preload(g_resources);

// load everything & display a loading screen
me.state.change(me.state.LOADING);
},
/* ---
callback when everything is loaded
--- */
loaded: function ()
{
// set the "Play/Ingame" Screen Object
   me.state.set(me.state.PLAY, new PlayScreen());
     
    // add our player entity in the entity pool
    me.entityPool.add("aluno", PlayerEntity);
     
    // enable the keyboard
    me.input.bindKey(me.input.KEY.LEFT,  "left");
    me.input.bindKey(me.input.KEY.RIGHT, "right");
me.input.bindKey(me.input.KEY.UP, "up");
me.input.bindKey(me.input.KEY.DOWN, "down");
      
    // start the game 
    me.state.change(me.state.PLAY);
},
mapSettings: function()
{
me.game.onLevelLoaded = this.mapSettings.bind(this);
var spawnPoints = me.game.getEntityByName('spawnpoint');
        var player = me.game.getEntityByName('aluno');
        $.each( spawnPoints, function( index, obj ) {
            if( obj.fromMap == me.gamestat.getItemValue('lastmap') ) {
                player[0].pos.x = obj.pos.x;
                player[0].pos.y = obj.pos.y;
            }
        });

        me.gamestat.setValue('lastmap', me.levelDirector.getCurrentLevelId() ); 
}

}; // jsApp

and in tiled is 

Jason Oster

unread,
Sep 5, 2012, 12:22:46 PM9/5/12
to mel...@googlegroups.com
Hi Rafael,

You will need to add the InvisibleEntity class to the entity pool with a name of "spawnpoint". Add this along side the other `entityPool` call in `jsApp.onload`:

me.entityPool.add("spawnpoint", me.InvisibleEntity);

me.entityPool.add("spawnpoint", me.InvisibleEntity);
Message has been deleted

Rafael Almeida

unread,
Sep 11, 2012, 1:59:57 PM9/11/12
to mel...@googlegroups.com
Thanks Jason, but now no error message appears and no updating of the position of the player, I think is correct I can not see what's wrong

Jason Oster

unread,
Sep 11, 2012, 2:21:48 PM9/11/12
to mel...@googlegroups.com
I think I see what's wrong. Your code has: me.gamestat.getItemValue('lastmap') But the object in your screenshot has 'frommap'. Make sure those strings are the same.

Also, try to familiarize yourself with the debugger in your browser (especially break points and single-stepping), it will help you spot these kinds of errors.

Jason Oster

unread,
Sep 11, 2012, 2:26:23 PM9/11/12
to mel...@googlegroups.com
Ahh, I made a mistake! The code I pointed out is actually ok. But there is a real problem; this line needs to be in the `loaded` function:

me.game.onLevelLoaded = this.mapSettings.bind(this);

Rafael Almeida

unread,
Sep 12, 2012, 7:05:23 AM9/12/12
to mel...@googlegroups.com
when i put  me.game.onLevelLoaded = this.mapSettings.bind(this);  in loaded show error  Uncaught ReferenceError: $ is not defined  need put  me.game.onLevelLoaded = this.mapSettings.bind(this); in mapSettings to no show error

Rafael Almeida

unread,
Sep 12, 2012, 7:17:28 AM9/12/12
to mel...@googlegroups.com
and need switch page when load map(I saw it when I switched between the code and the game) every map loaded show error  Uncaught ReferenceError: $ is not defined 
Message has been deleted

Rafael Almeida

unread,
Sep 12, 2012, 7:40:42 AM9/12/12
to mel...@googlegroups.com
when i put value type  player[0].pos.x = 10; and in y the player get this position for exemple when go to library and back to university the position in university is (10,10) so pass in code idk about obj

Jason Oster

unread,
Sep 12, 2012, 1:58:35 PM9/12/12
to mel...@googlegroups.com
Actually that is what you want! It means the person who posted that code is using a library like jQuery and you are not. Fix the code by replacing the jQuery-style loop with something else, but leave the me.game.onLevelLoaded line where I recommended.

Replace the $.each line with:

spawnPoints.forEach(function (obj)) {

You might also want to add this code to the top of the JS file, if you want to support Internet Explorer:

if (!Array.prototype.forEach) {
    Array.prototype.forEach = function (callback, scope) {
        for (var i = 0, j = this.length; j--; i++) {
            callback.call(scope || this, this[i], i, this);
        }
    };
}

In fact, I will add this code directly to melonJS, because it is very useful.

Rafael Almeida

unread,
Sep 12, 2012, 2:36:11 PM9/12/12
to mel...@googlegroups.com
I`m testing now already put me.game.onLevelLoaded = this.mapSettings.bind(this);  in loaded and change $.each for

spawnPoints.forEach(function (obj) {
            if (obj.fromMap == me.gamestat.getItemValue("lastmap")) {
                player[0].pos.x = obj.pos.x;
                player[0].pos.y = obj.pos.y;
            }
        });

and put code for IE in top but yet no show error and not work change position
note: token ) I change for final cause show a error  of  Uncaught SyntaxError: Unexpected token )

Jason Oster

unread,
Sep 12, 2012, 9:03:55 PM9/12/12
to mel...@googlegroups.com
At this point, I recommend using a breakpoint in your debugger to track down the remaining issue.

Rafael Almeida

unread,
Sep 19, 2012, 8:49:29 AM9/19/12
to mel...@googlegroups.com

Hi can make in tutorial a example doing transition between maps

I tried and still not get it, an example would help to analyze what I'm doing wrong

Jason Oster

unread,
Sep 19, 2012, 5:23:45 PM9/19/12
to mel...@googlegroups.com
The melonJS tutorial shows how to do level transitions in step 8:
http://www.melonjs.org/tutorial/tutorial_step8/index.html

The easiest way is to use a `me.LevelEntity` in your map and set its properties like in the screenshot: http://www.melonjs.org/tutorial/media/step8_next_level.png When the player entity touches it, the level will transition.

Or if you want to do the transition in pure code, you will want to use the `me.game.viewport.fade[In|Out]` methods in your ScreenObject. Like this: https://bitbucket.org/parasyte/neverwell-moor/src/c6f5b8715267/js/objects/screens.js#cl-93
Reply all
Reply to author
Forward
0 new messages