by jane kim(김해인) 2015.10.11에 작성: Vector개념을 배우고 이를 코드로 작성해 보았습니다..
코드 실행: https://www.khanacademy.org/computer-programming/pvector-instance/6479887750266880
/**
Try to catch the ball! It's harder when you move, but easy when you stay..... :)
Line 37: The reason why I used constrain() is because sometimes(or mostly) when you move your mouse in further directions, the ball can get off the canvas. Making the user a bit fustrated.
So, I just used constrain() to command the code where the ball can go without further ado.(it can only move inside the canvas!)
*/
background(97, 237, 255);
//I'm puting this in a function just in case somebody tweaks this code and gets an error. (Nobody wants that to happen!)
var ball = function(x, y) {
translate(x, y);
noStroke();
fill(255, 0, 0);
ellipse(0, 0, 30, 30);
fill(255, 255, 255);
arc(0, 0, 30, 30, 0, 180);
fill(0, 0, 0);
ellipse(0, 0, 5, 5);
};
mouseMoved = function() {
background(97, 237, 255);
//Creating two new PVectors, mouse and center.
/* The mouse is a vector showing us where the mouse is, and the center is just the center of the canvas.(In vector scale!) */
var mouse = new PVector(mouseX, mouseY);
var center = new PVector(width/2, height/2);
/* The mouse.sub(center) is in order to let the ball to fallow the mouse. Without it, it will go away twice from the position the mouse is currently on.
NOTE: mouse.mult(3) is to make distances from the mouse and the ball 3 times further.*/
mouse.sub(center);
mouse.mult(3);
//Since translate() is not with either pushMatrix() or popMatrix(), we have to reset the code by using resetMatrix().
resetMatrix();
translate(width/2, height/2);
ball(constrain(mouse.x, -185, 185), constrain(mouse.y, -185, 185));
};
/**
Note: This is just a practice program for my vector skills, not for khantober!
*/
by jane kim
'칸아카데미 > Advanced JS' 카테고리의 다른 글
칸아카데미>>Nomal distribution of random numbers (0) | 2015.10.03 |
---|---|
칸아카데미>>probability & non-uniform distributions (0) | 2015.10.02 |
Khan academy >> Random Walker (0) | 2015.10.02 |