Thursday, February 7, 2013

Dirty Rotation When Dragging

‹prev | My Chain | next›

I think that I have settled on the mouse event listener that I want to use in the most recent candidate game for Gaming JavaScript. I have a working library that allows the drag event to look like the following:
  var ramp = {
    startAt: function(location) {
      this.mesh = new Physijs.ConvexMesh( /* ... */ );
      // ...
      this.addMouseHandler();
    },
    addMouseHandler: function() {
      var mesh = this.mesh;
      mesh.addEventListener('drag', function(event) {
        mesh.__dirtyPosition = true;
        mesh.position.x = mesh.position.x + event.x_diff;
        mesh.position.y = mesh.position.y + event.y_diff;      
      });
    },
    // ...
  };
It relies on mesh being lexically scoped inside the addMouseHandler() method. As I have discussed, this might not look ideal to experienced JavaScripters, but it seems preferable to inflicting extensive this damage on kids. That's right, I am thinking of the kids.

There is still work to be done in that library. I actually need to extract it into a library. The code could be a little cleaner. I should probably generalize it to work with any Three.js object instead of only Physijs convex meshes. But I could use a break from it, if only for a night.

Tonight, I would like to add the ability to rotate the ramps in the game in addition to dragging them around the screen:


So I add a mouse handler that looks for the letter R to be pressed while the mesh is active (has been clicked):
  var ramp = {
    startAt: function(location) {
      this.mesh = new Physijs.ConvexMesh( /* ... */ );
      // ...
      this.addMouseHandler();
      this.addKeyHandler();
    },
    addMouseHandler: function() {
      // ...
    },
    addKeyHandler: function() {
      var mesh = this.mesh;
      document.addEventListener('keypress', function(event) {
        if (!mesh.isActive) return;
        if (event.keyCode != 114) return;
        mesh.__dirtyRotation = true;
        mesh.rotation.set(0,0,mesh.rotation.z + 0.1);
      });
    },
    // ...
  };
It remains a hassle to set the __dirtyRotation flag, but Physijs rightly requires that this be set when doing something that violates the laws of physics (like immediately changing the rotation of an object).

Anyhow, this works just fine... except when the physics engine is active. When physics is running, rotation works:


But if I then try to move the ramp, it somehow immediately ends up back in the original spot and rotation. It is as if the __dirtyPostion and __dirtyRotation flags are being ignored, but only when performing the drag operations that I have added to the mesh. If I only move the ramps, then nothing happens, but somehow introducing rotation is causing the problem. Stumped, I call it a night, but will pick back up tomorrow trying to figure out where I am going wrong.


Day #655

No comments:

Post a Comment