Search code examples
javascriptpaperjs

Move path onkeydown


I am trying to move a path.Circle on keydown in paperjs but it doesn't work and I can't spot the mistake.

Here is the code and this is link to the sketch.

var rect = new Path.Rectangle({
  point: [0, 0],
  size: [view.size.width, view.size.height],
  strokeColor: 'white',
  selected: true
});

rect.sendToBack();
rect.fillColor = 'blue';

var beach = new Path.Rectangle({
  point: [0, 0],
  size: [view.size.width, view.size.height / 5],
  strokeColor: 'white',
  selected: true
});

beach.fillColor = "yellow";

var boat = new Path.Circle(new Point(xpoint, ypoint), 30);
boat.fillColor = "black";

xpoint = 100;
ypoint = 300;

function onKeyDown(event) {
  if (event.key == 'a') {
    xpoint -= 10;
  }

  if (event.key == 'd') {
    xpoint += 10;
  }

  if (event.key == 'w') {
    ypoint -= 10;
  }

  if (event.key == 's') {
    ypoint += 10;
  }
}

Solution

  • You're just setting the values of the variables that you originally used in creating the boat, but it's not changing the boat at all.

    var x = 10,
        y = 10,
        boat = new Boat(x, y);    //pseudocode
    
    // now setting x doesn't do anything at all. The value was already
    // passed to boat, boat doesn't retain a reference to x 
    x = 20;
    

    Instead, change the variable and then modify boat directly. I don't know paperjs well, but the following seems to work:

    function onKeyDown(event) {
       if(event.key == 'a') {
          xpoint -= 10;
       }
       // ...
    
       boat.setPosition(xpoint, ypoint)
    }