Jump to content

best way to move a sprite


timmyelliot
 Share

Recommended Posts

Hi,

 

I was trying to move a sprite using keyboard 'a' and 'd,' using the sprite sample from the playgroud saved here:

 

 http://www.babylonjs-playground.com/#14OAYQ#12

(lines 37 - 46, also listed below)

 

The movement looks very choppy and flickers, is there a better way of doing this so that the sprite appears to move more smoothly?

 

scene.actionManager = new BABYLON.ActionManager(scene);
 
scene.actionManager.registerAction(
new BABYLON.ExecuteCodeAction(BABYLON.ActionManager.OnKeyDownTrigger, function (evt) {
    if (evt.sourceEvent.keyCode == 65) {
        player.position.x = player.position.x + .05;
        player.invertU = false;
    }
    if(evt.sourceEvent.keyCode == 68){
      player.position.x = player.position.x + -.05; 
      player.invertU = true;
   }
}));
 
Link to comment
Share on other sites

Hello, 

 

You can use registerBeforeRender (that will be called 60 times per seconds). I used window events keydown and keyup to trigger the movement (cause it's a copy paste from a project of mine), but it should work too with ActionManager and OnKeyDownTrigger.

 

http://www.babylonjs-playground.com/#14OAYQ#13

 

Good luck :)

Link to comment
Share on other sites

It's choppy because it's running off the browser's keyDown events. When you hold down a key, the OS normally fires one key event, then pauses, then fires more at regular intervals, depending on OS settings. It works exactly the same as when you're typing in a text field.

 

To get regular movement you need to use both keyDown and keyUp listeners to track whether keys are down (there is no "isKeyPressed" in JS).

Link to comment
Share on other sites

Incidentally, a while back I wrote a library to manage things like this.

https://github.com/andyhall/game-inputs

 

With that, you'd do something like:

var inputs = require('game-inputs')()inputs.bind( 'moveLeft',  'A', '<left>' )inputs.bind( 'moveRight', 'D', '<right>' )scene.registerBeforeRender(function() {  if (inputs.state.moveLeft) { /* ... */ }  if (inputs.state.moveRight) { /* ... */ }})
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...