Advertisement
Just_Random_Guy

3D Cubes and movement part 2

Jan 21st, 2018
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. // Creating variables
  2. var x=[], y=[], z=[];
  3.  
  4. for (let i=0; i<20*8; i+=8){
  5. x[i+6] = x[i+4] = x[i+2] = x[i] = Math.random()*800-400;
  6. y[i] = y[i+1] = y[i+2] = y[i+3] = Math.random()*600-300;
  7. z[i] = z[i+1] = z[i+4] = z[i+5] = Math.random()*5;
  8. x[i+7] = x[i+5] = x[i+3] = x[i+1] = x[i]+50;
  9. y[i+7] = y[i+6] = y[i+5] = y[i+4] = y[i]+50;
  10. z[i+7] = z[i+6] = z[i+3] = z[i+2] = z[i]+0.15;
  11. }
  12.  
  13. function segment3d(ind1, ind2){
  14. if (z[ind1]>=0 && z[ind2]>=0){
  15. context.beginPath();
  16. context.moveTo(x[ind1]/z[ind1] + 400, y[ind1]/z[ind1] + 300);
  17. context.lineTo(x[ind2]/z[ind2] + 400, y[ind2]/z[ind2] + 300);
  18. context.stroke();
  19. }
  20. }
  21.  
  22. function drawCube(i){
  23. segment3d(i, i+1);
  24. segment3d(i+2, i+3);
  25. segment3d(i+4, i+5);
  26. segment3d(i+6, i+7);
  27. segment3d(i, i+4);
  28. segment3d(i+1, i+5);
  29. segment3d(i+2, i+6);
  30. segment3d(i+3, i+7);
  31. segment3d(i, i+2);
  32. segment3d(i+1, i+3);
  33. segment3d(i+4, i+6);
  34. segment3d(i+5, i+7);
  35. }
  36.  
  37. function rotateX(i, d){
  38. var x1 = x[i];
  39. var z1 = z[i]*375;
  40. var angle = Math.atan2(z1, x1);
  41. angle+=d;
  42. var dist = Math.sqrt(x1*x1 + z1*z1);
  43. var x_new = Math.cos(angle)*dist;
  44. var z_new = Math.sin(angle)*dist;
  45. x[i] = x_new;
  46. z[i] = z_new/375;
  47. }
  48.  
  49. function rotateY(i, d){
  50. var y1 = y[i];
  51. var z1 = z[i]*375;
  52. var angle = Math.atan2(z1, y1);
  53. angle+=d;
  54. var dist = Math.sqrt(y1*y1 + z1*z1);
  55. var y_new = Math.cos(angle)*dist;
  56. var z_new = Math.sin(angle)*dist;
  57. y[i] = y_new;
  58. z[i] = z_new/375;
  59. }
  60.  
  61. function update() {
  62. for (let i=0; i<20*8; ++i){
  63. if (isKeyPressed[key_up]){rotateY(i, -0.01);}
  64. if (isKeyPressed[key_down]){rotateY(i, 0.01);}
  65. if (isKeyPressed[65]){x[i]+=5;}
  66. if (isKeyPressed[68]){x[i]-=5;}
  67. if (isKeyPressed[87]){z[i]-=0.05;}
  68. if (isKeyPressed[83]){z[i]+=0.05;}
  69. if (isKeyPressed[key_left]){rotateX(i, -0.01);}
  70. if (isKeyPressed[key_right]){rotateX(i, 0.01);}
  71. }
  72. }
  73.  
  74. function draw() {
  75. for (let i=0; i<20*8; i+=8){
  76. drawCube(i);
  77. }
  78. };
  79.  
  80. function keyup(key) {
  81. // Show the pressed keycode in the console
  82. console.log("Pressed", key);
  83. };
  84.  
  85. function mouseup() {
  86. // Show coordinates of mouse on click
  87. console.log("Mouse clicked at", mouseX, mouseY);
  88. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement