bio photo

Email

####Intro Ellipses are easier to manipulate compared to triangles because they only have one set of cartesian co-ordinates. Here I introduce variables to represent co-ordinates of a triangle with the thought of doing more with my spaceship.


Here’s the program in action

Animation

####Triangle - spaceship

Old co-ordinates (mouse dependent)

  // center space ship moves to mouse
  stroke(255);
  noFill();
  triangle(mouseX+65,mouseY+65,mouseX+75,mouseY+75,mouseX+85,mouseY+45);

Introducing new variables and co-ordinates for spaceship:

var t = {
  x1 : 65, y1 : 65, x2 : 75, y2 : 75, x3 : 85, y3 : 45
};

// triangle space ship 
  stroke(255);
  noFill();
  triangle(t.x1, t.y1 , t.x2, t.y2 ,t.x3 ,t.y3);

####Animation using p5 - if statements

  1. Read J. Kuiphoff’s Animation using p5.js.
  2. Felt animation using keyboard driven actions are closer to actual game play in Asteroids.
  3. In particular, Fluid Movements, which makes use of three new concepts
    (i) dx > distance between actual position and intended position
    (ii) targetX > intended destination of object
    (iii) using var easing and if statements
  4. An open source code is manipulated to introduce fluid movements. Here’s my version of it (keeping in view the new triangle variables),
// calculate new y1,y2,y3
  var dy1 = targetY1 - t.y1;
  if (abs(dy1)>1){
    t.y1 += dy1 * easing;
  }
  var dy2 = targetY2 - t.y2;
  if (abs(dy2)>1){
    t.y2 += dy2 * easing;
  }
  var dy3 = targetY3 - t.y3;
  if (abs(dy3)>1){
    t.y3 += dy3 * easing;
  }
// calculate new x1,x2,x3
  var dx1 = targetX1 - t.x1;
  if (abs(dx1)>1){
    t.x1 += dx1 * easing;
  }
  var dx2 = targetX2 - t.x2;
  if (abs(dx2)>1){
    t.x2 += dx2 * easing;
  }
  var dx3 = targetX3 - t.x3;
  if (abs(dx3)>1){
    t.x3 += dx3 * easing;

Animation using p5 - keyPressed() Function

  1. The function keyPressed() let’s you assign codeblocks to events driven by key-strokes.
  2. I have defined the following targetX and targetY variables in relation to the triangle’s co-ordinates.
  3. numPixels is a variable which determines the distance by pixel a key stroke moves the spaceship (in my program, 10px)
  4. PROBLEM: I can only get the spaceship to move across one diagonal axis.
  5. PROBLEM: I can’t figure out how to put in action the RIGHT_ARROW and LEFT_ARROW actions.
function keyPressed(){
   // Up key
   if (keyCode == UP_ARROW){
     targetX1 = t.x1 - numPixels;
     targetY1 = t.y1 - numPixels;
     targetX2 = t.x2 - numPixels;
     targetY2 = t.y2 - numPixels;
     targetX3 = t.x3 - numPixels;
     targetY3 = t.y3 - numPixels;
   }
  
   // Down key
   if (keyCode == DOWN_ARROW){
     targetX1 = t.x1 + numPixels;
     targetY1 = t.y1 + numPixels;
     targetX2 = t.x2 + numPixels;
     targetY2 = t.y2 + numPixels;
     targetX3 = t.x3 + numPixels;
     targetY3 = t.y3 + numPixels;
   }
}

Here’s the program in action

Animation