Analysis of a body sliding down an inclined plane – an object-oriented approach
The example should look like the animation below:
Click (tap) the small square at the top of the inclined plane and drag it up or down. A double click or the r key puts the body back at the start.
The basic animation of a body sliding down an inclined plane described earlier, where the user can only watch and cannot affect the animation, now has a new option: moving the small square at the top of the inclined plane increases or decreases its height, and with it the slope angle. These features were also added: resetting, for both desktop and mobile devices, and showing the basic quantities by drawing text on the screen. To put the animation into a web page, JavaScript code was also added to improve its functionality. The code described in the basic version of the animation was rearranged so that it could be translated into JavaScript with the JavaScript file processing.js .
See a simulation made with p5.js on the web page (in Serbian): simulacije.svetprogramiranja.com/klizanje_tela_niz_strmu_ravan
How to use the animation
1) Selecting and deselecting the small square. Clicking the small square in the corner of the inclined plane with the mouse (the mouseClick event) or pressing it with a finger (the touchStart event) selects it, and it turns red. Clicking anywhere on the animation outside the small square deselects it.
2) Moving the small square (changing the height of the inclined plane). After it is selected, the small square can be moved in several ways, depending on the device: on a desktop computer or a tablet with a mouse, it can be dragged (mouseDragged) along the Y axis to change its position, and with it the height of the inclined plane, or you can click once above or below its previous position. If a keyboard is available, the UP or DOWN arrow keys also change the height H of the inclined plane.
On mobile devices and tablets, after selecting it, you can move the small square with your finger (the touchMove event).
As the position of the small square changes, the height H of the inclined plane changes, and so does the slope. In the default position, for the defined values:
F tr = μ * N;
gde je
koeficijent trenja μ = 0,
2 i
masa m = 1kg sila trenja F tr = μ * N;
ne dozvoljava da se telo kreće, jer za početni nagib od α = 4, o koji se dobija pomoću formule α = atan(H / L);
sila gravitacije duž kose ravni nije dovoljno velika da savlada silu trenja
As the height of the inclined plane increases, the magnitude of this component of gravity (the weight of the body) also changes, so at some moment it becomes greater than the friction force, and then the body starts to slide down the inclined plane. So the condition for sliding is:
F a >= F tr,
gde je F a komponenta sile gravitacije duž strme ravni
3) Resetting. The animation can be reset with the 'r' key on the keyboard (desktop and tablet), or with a double tap on the animation (mobile devices and tablets). When it resets, the quantities return to their starting values and the drawing loop starts again, but the height of the plane stays the last one set. As a reminder, when the body reaches the end position at the bottom of the inclined plane, the loop stops.
4) Writing text. To draw text, we first need to create a font f (PFont). Then, with the method textFont(f) (from the basic Processing library), we set the font we created, passing it as a parameter to textFont(). Finally, the text is written with the Processing method text(textZaIspis, x,y), whose parameters are the text to write and its position on the screen, given by the coordinates x and y.
Analysis of the code
Since the PShape object and everything related to drawing shapes this way is not supported in JavaScript, this had to be done another way, which is shown in the following pictures. The old code is only commented out, so that it can be compared with the new code. If the application is used on desktop computers, PShape can be used. First, let's look at the changes in the class Telo (Body), shown in the picture below:
Code from figure 1: Analysis of a body sliding down an inclined plane – example code – the Telo class (1)
class Telo {
// PShape rect;
float fi = 0;
PVector polozaj;
float m = 10;
float koefTrenja = 0.2;
PVector v;
PVector a;
PVector Tx;
PVector tr;
PVector N;
PVector Fr;
public Telo() {
// rect = createShape(RECT, 0, 0, w, h);
// rect.setFill(color(0, 0, 255));
polozaj = new PVector(0, 0);
v = new PVector(0, 0);
a = new PVector(0, 0);
tr = new PVector(0, 0);
}
We can see that the declaration of the body object as a PShape is commented out because, as already mentioned, this code will be uploaded to a website and compiled there as JavaScript, where PShape is not supported. Instead, the body will be created with beginShape() - vertex- endShape(). Read how to create your own (custom) shape object on the page:
processing.org/reference/beginShape_.htmlIn the main part of the sketch, these variables are declared: the slope angle of the inclined plane fi, the vectors of position, velocity v and acceleration a, the component of the body's weight along the slope Tx, the normal force with which the body acts on the surface N, the resultant force Fr, the mass m and the friction coefficient. In the constructor the vectors are created and given starting values, with components whose magnitudes are zero.
.
Code from figure 2: Analysis of a body sliding down an inclined plane – example code – the Telo class (2)
void sile() {
/* weight – the component along the inclined plane */
Tx = new PVector(m * G * sin(fi), 0);
/* reakcija podloge */
N = new PVector(0, m * G * cos(fi));
/* friction */
tr = new PVector(v.x, v.y);
if (v.x > 1)
tr.normalize();
// tr = v.normalize();
if (tr != null)
tr.mult(-1);
float trenjeInt = koefTrenja * N.mag();
if (tr != null)
tr.mult(trenjeInt);
/* adding the forces */
Fr = new PVector();
if (v.mag() == 0 && Tx.mag() > trenjeInt || v.mag() != 0) {
Fr.add(Tx);
Fr.add(tr);
}
}
Inside the method sile() (forces), the force vectors that affect the motion of the body are created. These are defined: Tx – the component of the force in the x direction, i.e. parallel to the slope, the reaction of the surface N, the friction force tr and finally the resultant Fr. The friction force acts along the velocity vector, so it is first created from that vector. The function normalize() turns that vector into a unit vector. Then the vector is multiplied by -1 with the function mult, because it points opposite to the velocity vector. Finally, it is multiplied by its magnitude, computed as the product of the friction coefficient and the magnitude of the normal force on the surface. You can read more about vectors and the functions of the PVector class on the page: Vectors in ProcessingThe resultant Fr is computed when the condition for the body to start moving is met, which happens when the component of the weight in the x direction becomes greater than the friction force: Tx.mag()>trenjeInt
Code from figure 3: Analysis of a body sliding down an inclined plane – example code – the Telo class (3)
void kretanje() {
/* defining the acceleration of the body */
a = PVector.div(Fr, m);
a.mult(RAZMERA);
PVector dv = PVector.div(a, BROJ_FREJMOVA); // do not use the variable frameRate for the number of frames
if (stop) {
v.mult(0);
stop = false;
}
v.add(dv);
PVector dx = PVector.div(v, BROJ_FREJMOVA);
polozaj.add(dx);
/* end of motion */
}
void render() {
// shape(telo.rect);
fill(0, 0, 255);
rect(0, 0, w, h);
}
void granicniUslovi() {
float granicnaDuzina = (float) Math.sqrt(H * H + L * L) - 100;
if (polozaj.x >= granicnaDuzina) {
stop = true;
}
}
void reset() {
polozaj = new PVector(0, 0);
v = new PVector(0, 0);
a = new PVector(0, 0);
tr = new PVector(0, 0);
}
}
The whole program in one piece (3 pictures joined)
class Telo {
// PShape rect;
float fi = 0;
PVector polozaj;
float m = 10;
float koefTrenja = 0.2;
PVector v;
PVector a;
PVector Tx;
PVector tr;
PVector N;
PVector Fr;
public Telo() {
// rect = createShape(RECT, 0, 0, w, h);
// rect.setFill(color(0, 0, 255));
polozaj = new PVector(0, 0);
v = new PVector(0, 0);
a = new PVector(0, 0);
tr = new PVector(0, 0);
}
void sile() {
/* weight – the component along the inclined plane */
Tx = new PVector(m * G * sin(fi), 0);
/* reakcija podloge */
N = new PVector(0, m * G * cos(fi));
/* friction */
tr = new PVector(v.x, v.y);
if (v.x > 1)
tr.normalize();
// tr = v.normalize();
if (tr != null)
tr.mult(-1);
float trenjeInt = koefTrenja * N.mag();
if (tr != null)
tr.mult(trenjeInt);
/* adding the forces */
Fr = new PVector();
if (v.mag() == 0 && Tx.mag() > trenjeInt || v.mag() != 0) {
Fr.add(Tx);
Fr.add(tr);
}
}
void kretanje() {
/* defining the acceleration of the body */
a = PVector.div(Fr, m);
a.mult(RAZMERA);
PVector dv = PVector.div(a, BROJ_FREJMOVA); // do not use the variable frameRate for the number of frames
if (stop) {
v.mult(0);
stop = false;
}
v.add(dv);
PVector dx = PVector.div(v, BROJ_FREJMOVA);
polozaj.add(dx);
/* end of motion */
}
void render() {
// shape(telo.rect);
fill(0, 0, 255);
rect(0, 0, w, h);
}
void granicniUslovi() {
float granicnaDuzina = (float) Math.sqrt(H * H + L * L) - 100;
if (polozaj.x >= granicnaDuzina) {
stop = true;
}
}
void reset() {
polozaj = new PVector(0, 0);
v = new PVector(0, 0);
a = new PVector(0, 0);
tr = new PVector(0, 0);
}
}
Further in the class Telo, figure 3 shows 3 more methods: kretanje() (motion), render() and reset().
The method kretanje() defines the changes of the acceleration, velocity and position of the body between two calls of the draw() method, i.e. every 1/FrameRate seconds.
The change of acceleration is caused by the change of the resultant force that causes this acceleration: a=PVector.div(Fr/m), i.e. (a=Fr/m – Newton's 2nd law).
Since the measures are in px, not in meters, a scale is used to make the animation more realistic.
The change of acceleration then changes the velocity, and the change of velocity changes the position; this is computed further in the method kretanje().
The method granicniUslovi (boundary conditions) has not changed compared with the basic version of the task.
The method reset() returns the physical quantities to their starting values, as they were defined in the constructor.
The main part of the sketch can be seen in figures 4–11.
Code from figure 4: Analysis of a body sliding down an inclined plane – example code – the main sketch (1)
// PShape tlo;
// PShape xOsa;
// PShape yOsa;
// PShape M;
float H = 50;
float L = 600;
float ugao;
Telo telo;
float w, h;
float fi;
// float x = 0;
boolean pritisnuta = false;
boolean stop = false;
static final float G = 9.81;
static final int RAZMERA = 20;
static final int BROJ_FREJMOVA = 20;
PFont f;
String dogadjaj;
float pY;
Here too, the objects that were created as PShape objects in the basic version (commented out) are now created with beginShape() and endShape(). These are the objects that represent the ground and the small square (M) used to change the height of the inclined plane. The other variables declared as global are, in order: the height of the slope H and the length of the inclined plane L (H and L are the legs of the right triangle that represents the inclined plane, colored green in the animation, while the plane itself is the hypotenuse of the triangle).
Next are defined: the slope angle ugao (a mistake – this line should be deleted), the sliding body telo, w and h, the width and height of the body, and fi, the slope angle of the inclined plane in radians.
The boolean variables stop and pritisnuta (pressed): stop says whether the body has reached the bottom of the inclined plane and the animation has stopped, while the variable pritisnuta says whether the control point (the small square M) is selected or not. When it is selected, it can be moved by dragging the mouse up or down, which increases or decreases the height of the inclined plane.
The constants G, RAZMERA and BROJ_FREJMOVA define the gravitational constant, the scale (px/m) and the number of frames per second, in order.
The variables f, dogadjaj and pY are also defined. The variable f is used to define the font for writing text on the screen. The String variable dogadjaj (event) shows the kind of event (e.g. mouseClick), which is shown as text in the animation (see figure 6 below).
The variable pY remembers the previous value of the Y coordinate of the control point M.
Figure 4 also shows part of the setup() method. This part is explained in the basic version of the animation.
Code from figure 5: Analysis of a body sliding down an inclined plane – example code – the main sketch (2)
void setup() {
size(640, 327, P2D);
rectMode(CENTER);
w = 80;
h = 50;
frameRate(20);
// tlo = createShape(TRIANGLE, 0, height - H, 0, height, L, height);
// M = createShape(RECT, 0, 0, 10, 10);
telo = new Telo();
ugaoNagiba();
// xOsa = createShape(LINE, 0, 0, 100, 0);
// yOsa = createShape(LINE, 0, 0, 0, 100);
f = createFont("Arial", 14, true); // the font is created
dogadjaj = "no events";
pY = height - H;
}
void ugaoNagiba() {
fi = atan(H / L);
telo.fi = fi;
}
Next, figure 5 shows the complete setup() method and part of the draw() method. Here we also see the commented-out code that used to refer to the objects of the ground and the control square M. In the setup() method, after the body is created as an object of the class Tacka, the method ugaoNagiba() (slope angle) is called; it computes the slope angle from the height and length of the ground, H and L.
Then the font f is created, the text for showing events is defined, and the starting value of the y coordinate of the body is computed.
Inside the draw() method, after the background color and the fill color are set, you can see the start of beginShape(TRIANGLE_STRIP). This will create and draw the ground. This continues below (figure 6).
Code from figure 6: Analysis of a body sliding down an inclined plane – example code – the main sketch (3)
void draw() {
// tlo = createShape(TRIANGLE, 0, height - H, 0, height, L, height);
// M = createShape(RECT, 0, 0, 10, 10);
background(200);
fill(0, 0, 255);
// tlo.setFill(color(0, 255, 0));
// shape(tlo);
beginShape(TRIANGLE_STRIP);
fill(0, 255, 0);
vertex(0, height - H);
vertex(0, height);
vertex(L, height);
endShape(CLOSE);
translate(0, height - H - h / 2); // moves the origin of the coordinate system to the height height-H-h/2
/* if (pritisnuta) {
// M.setFill(color(200, 0, 0));
// M.setStroke(color(255, 0, 0));
fill(255, 0, 0);
} else {
// M.setFill(color(0, 200, 0));
// M.setStroke(color(0, 255, 0));
fill(0, 0, 255);
} */
pushMatrix();
translate(0, h / 2);
// shape(M);
beginShape(QUADS);
if (pritisnuta) {
fill(255, 0, 0);
} else {
fill(0, 0, 255);
}
vertex(0, 5);
vertex(10, 5);
vertex(10, -5);
vertex(0, -5);
endShape(CLOSE);
popMatrix();
Figure 6 shows the part of the draw() method that creates and draws the ground, as well as the control square M. For the ground, between beginShape(TRIANGLE_STRIP) and endShape(CLOSE), first the fill color is set with the method fill(), green in this case, and then the vertex() method draws lines between the points of the triangle. The coordinates of the points are the parameters of the vertex method. The parameter CLOSE in endShape() says that this is a closed polygon, in this case a triangle, because there are only 3 points. Unlike the ground, for drawing the small square vertex is called 4 times, between beginShape(QUAD) and endShape(CLOSE).
The flags TRIANGLE_STRIP and QUAD say that the area of the triangle (the ground) and of the square (M) are made by joining consecutive triangles or quadrilaterals.
Before drawing the small square M, the coordinate system is translated from the top left corner of the screen to the top of the ground, i.e. by height-H-h/2.
This means that the coordinates for drawing the points of the control square are now measured in the new coordinate system. These changes are used to draw the small square, but afterwards the state goes back to the old one, because this code is written between pushMatrix() and popMatrix().
Read more about this in the article: processing.org/reference/pushMatrix_.html
Code from figure 7: Analysis of a body sliding down an inclined plane – example code – the main sketch (4)
pushMatrix();
fi = atan(H / L);
rotate(fi);
telo.sile();
telo.kretanje();
telo.granicniUslovi();
translate(100 + telo.polozaj.x, 0);
telo.render();
/* xOsa.setStroke(color(255, 255, 50));
yOsa.setStroke(color(255, 150, 50));
shape(xOsa);
shape(yOsa); */
stroke(255, 255, 50);
line(0, 0, 100, 0);
line(0, 0, 0, 100);
popMatrix();
translate(0, -height + H + h / 2); // puts the origin of the coordinate system back
// writing the data
textFont(f);
fill(30, 30, 50);
text("SELECT SQUARE AND PRESS 'UP or DOWN' FOR CHANGING H!", 130, 30);
text("OR SELECT SQUARE AND DRAG Y FOR CHANGING H!", 130, 55);
text("PRESS 'r' OR DOUBLE TOUCH FOR RESET!", 130, 80);
text("SPEED: " + nfs(telo.v.mag(), 4, 2) + " m/s,", 230, 105);
text("ANGLE: " + nfs(degrees(fi), 2, 1), 230, 130);
text("FRICTION FORCE: " + nfs(telo.tr.mag(), 2, 1) + "N", 230, 155);
text("KOEF. OF FRICTION: " + telo.koefTrenja, 230, 180);
text("EVENTS: " + dogadjaj, 230, 205);
if (stop) {
noLoop();
telo.reset();
}
}
Figure 7 shows the draw() method to the end. Next, between pushMatrix() and popMatrix(), the body is prepared and drawn, together with the axes of the current moving coordinate system, which moves with the body and has its origin at the center of the body.
The preparation is the rotation of the coordinate system by the angle fi, and then the methods defined in the class Telo are called in order: sile(), kretanje(), granicniUslovi(). These methods were explained earlier.
Before the body is drawn by calling the method render(), the coordinate system, besides the earlier rotation, is now also translated to the position above the top of the ground, at the start of the slope, where the body will actually start moving, i.e. sliding along the plane.
After the body is drawn, the coordinate system goes back to the old one, and then text is written on the screen with calls of the method text(). Using the method text and setting the font is described in the article processing.org/reference/text_.htmlFinally, the value of the boolean variable stop is checked. If it was set to true earlier inside the method granicniUslovi(), that means the body has reached the bottom of the inclined plane, so the animation loop stops and the values of the physical quantities are set to their starting values inside the method reset(), which is called from here.
Code from figure 8: Analysis of a body sliding down an inclined plane – example code – the main sketch (5). The keyPress event
void keyPressed() {
if (key == 'r') {
pritisnuta = false;
reset();
loop();
}
if (keyCode == UP) {
dogadjaj = "keyUP";
if (pritisnuta) {
int dH = 1;
H += dH;
ugaoNagiba();
}
}
if (keyCode == DOWN) {
dogadjaj = "keyDOWN";
if (pritisnuta) {
int dH = 1;
H -= dH;
ugaoNagiba();
}
}
}
Further in the main sketch, the method keyPressed() is defined, which handles the keys 'r' – for resetting, UP – for increasing the height of the inclined plane, and DOWN – for decreasing it. When the height H of the plane changes, the slope angle also changes, which is why the method of the same name is called.
Code from figure 9: Analysis of a body sliding down an inclined plane – example code – the main sketch (6). The events mouseClicked and mouseDragged. The method handleMove.
void mouseClicked() {
// println(mouseX + "," + mouseY);
dogadjaj = "mouseClicked";
if (!pritisnuta && (mouseX >= 0 && mouseX <= 10) && (mouseY >= height - H - 10 && mouseY <= height - H + 10)) {
pritisnuta = true;
} else if (pritisnuta) {
float dH = pY - mouseY;
promeniH(dH);
ugaoNagiba();
pY = mouseY;
pritisnuta = false;
}
}
void mouseDragged() {
dogadjaj = "mouseDragged";
if (pritisnuta) {
int dH = pmouseY - mouseY;
H += dH;
ugaoNagiba();
}
}
void handleMove(float dH) {
dogadjaj = "touchMove: " + dH;
if (pritisnuta) {
H += dH;
ugaoNagiba();
}
}
The method mouseClicked() is called when the mouse button is clicked on a desktop computer or tablet, or when a finger presses the screen on mobile devices and tablets, unless the default touch behavior is turned off – by default, a touch also calls mouseClicked(). This can be done by calling evt.preventDefault() in the JavaScript part of the application, where evt is an object of the class TouchEvent.
Read more about this in the article: developer.mozilla.org/en-US/docs/Web/API/Touch_eventsPart of the JavaScript code will be shown later in this article.
The method handleMove(float dH) is called from that JavaScript. It changes the height of the inclined plane by the value dH, passed to this method as a parameter, which is also computed in the JavaScript.
Code from figure 10: Analysis of a body sliding down an inclined plane – example code – the main sketch (7). The touchStart event. The methods handleDbClick, promeniH(), isPritisnuta().
void promeniH(float dH) {
H += dH;
}
void handleDbClick() {
dogadjaj = "DobleClick(reset)";
pritisnuta = false;
reset();
loop();
}
void touchStart(float mx, float my) {
dogadjaj = "touchStart ";
float granicaYMin = height - H - 10;
float granicaYMax = height - H + 10;
if ((mx >= 0 && mx <= 15) && (my >= granicaYMin && my <= granicaYMax)) {
pritisnuta = true;
} else {
pritisnuta = false;
}
}
boolean isPritisnuta() {
return pritisnuta;
}
void setPritisnuta(boolean p) {
pritisnuta = p;
}
void reset() {
telo.reset();
}
The whole program in one piece (7 pictures joined)
// PShape tlo;
// PShape xOsa;
// PShape yOsa;
// PShape M;
float H = 50;
float L = 600;
float ugao;
Telo telo;
float w, h;
float fi;
// float x = 0;
boolean pritisnuta = false;
boolean stop = false;
static final float G = 9.81;
static final int RAZMERA = 20;
static final int BROJ_FREJMOVA = 20;
PFont f;
String dogadjaj;
float pY;
void setup() {
size(640, 327, P2D);
rectMode(CENTER);
w = 80;
h = 50;
frameRate(20);
// tlo = createShape(TRIANGLE, 0, height - H, 0, height, L, height);
// M = createShape(RECT, 0, 0, 10, 10);
telo = new Telo();
ugaoNagiba();
// xOsa = createShape(LINE, 0, 0, 100, 0);
// yOsa = createShape(LINE, 0, 0, 0, 100);
f = createFont("Arial", 14, true); // the font is created
dogadjaj = "no events";
pY = height - H;
}
void ugaoNagiba() {
fi = atan(H / L);
telo.fi = fi;
}
void draw() {
// tlo = createShape(TRIANGLE, 0, height - H, 0, height, L, height);
// M = createShape(RECT, 0, 0, 10, 10);
background(200);
fill(0, 0, 255);
// tlo.setFill(color(0, 255, 0));
// shape(tlo);
beginShape(TRIANGLE_STRIP);
fill(0, 255, 0);
vertex(0, height - H);
vertex(0, height);
vertex(L, height);
endShape(CLOSE);
translate(0, height - H - h / 2); // moves the origin of the coordinate system to the height height-H-h/2
/* if (pritisnuta) {
// M.setFill(color(200, 0, 0));
// M.setStroke(color(255, 0, 0));
fill(255, 0, 0);
} else {
// M.setFill(color(0, 200, 0));
// M.setStroke(color(0, 255, 0));
fill(0, 0, 255);
} */
pushMatrix();
translate(0, h / 2);
// shape(M);
beginShape(QUADS);
if (pritisnuta) {
fill(255, 0, 0);
} else {
fill(0, 0, 255);
}
vertex(0, 5);
vertex(10, 5);
vertex(10, -5);
vertex(0, -5);
endShape(CLOSE);
popMatrix();
pushMatrix();
fi = atan(H / L);
rotate(fi);
telo.sile();
telo.kretanje();
telo.granicniUslovi();
translate(100 + telo.polozaj.x, 0);
telo.render();
/* xOsa.setStroke(color(255, 255, 50));
yOsa.setStroke(color(255, 150, 50));
shape(xOsa);
shape(yOsa); */
stroke(255, 255, 50);
line(0, 0, 100, 0);
line(0, 0, 0, 100);
popMatrix();
translate(0, -height + H + h / 2); // puts the origin of the coordinate system back
// writing the data
textFont(f);
fill(30, 30, 50);
text("SELECT SQUARE AND PRESS 'UP or DOWN' FOR CHANGING H!", 130, 30);
text("OR SELECT SQUARE AND DRAG Y FOR CHANGING H!", 130, 55);
text("PRESS 'r' OR DOUBLE TOUCH FOR RESET!", 130, 80);
text("SPEED: " + nfs(telo.v.mag(), 4, 2) + " m/s,", 230, 105);
text("ANGLE: " + nfs(degrees(fi), 2, 1), 230, 130);
text("FRICTION FORCE: " + nfs(telo.tr.mag(), 2, 1) + "N", 230, 155);
text("KOEF. OF FRICTION: " + telo.koefTrenja, 230, 180);
text("EVENTS: " + dogadjaj, 230, 205);
if (stop) {
noLoop();
telo.reset();
}
}
void keyPressed() {
if (key == 'r') {
pritisnuta = false;
reset();
loop();
}
if (keyCode == UP) {
dogadjaj = "keyUP";
if (pritisnuta) {
int dH = 1;
H += dH;
ugaoNagiba();
}
}
if (keyCode == DOWN) {
dogadjaj = "keyDOWN";
if (pritisnuta) {
int dH = 1;
H -= dH;
ugaoNagiba();
}
}
}
void mouseClicked() {
// println(mouseX + "," + mouseY);
dogadjaj = "mouseClicked";
if (!pritisnuta && (mouseX >= 0 && mouseX <= 10) && (mouseY >= height - H - 10 && mouseY <= height - H + 10)) {
pritisnuta = true;
} else if (pritisnuta) {
float dH = pY - mouseY;
promeniH(dH);
ugaoNagiba();
pY = mouseY;
pritisnuta = false;
}
}
void mouseDragged() {
dogadjaj = "mouseDragged";
if (pritisnuta) {
int dH = pmouseY - mouseY;
H += dH;
ugaoNagiba();
}
}
void handleMove(float dH) {
dogadjaj = "touchMove: " + dH;
if (pritisnuta) {
H += dH;
ugaoNagiba();
}
}
void promeniH(float dH) {
H += dH;
}
void handleDbClick() {
dogadjaj = "DobleClick(reset)";
pritisnuta = false;
reset();
loop();
}
void touchStart(float mx, float my) {
dogadjaj = "touchStart ";
float granicaYMin = height - H - 10;
float granicaYMax = height - H + 10;
if ((mx >= 0 && mx <= 15) && (my >= granicaYMin && my <= granicaYMax)) {
pritisnuta = true;
} else {
pritisnuta = false;
}
}
boolean isPritisnuta() {
return pritisnuta;
}
void setPritisnuta(boolean p) {
pritisnuta = p;
}
void reset() {
telo.reset();
}
Figure 10 shows the methods promeniH() (change H), setPritisnuta() and reset(), whose purpose is clear. The method touchStart() is called from the JavaScript code when the user presses the screen with a finger. The parameters mx and my are the coordinates of the point on the screen that the user touched. Inside the method we check whether this point is inside the control square or not, and set the variable pritisnuta to true or false.
The method handleDbClick() is a handler method called from JavaScript when the user quickly taps 2 times in a row. It does the same as the method reset(), which is called when the user presses the 'r' key on the keyboard.
JavaScript code in the application with the sliding body animation: "StrmaRavanObjektno"
The JavaScript code is in the file main.js and is shown in parts in figures 11–14.
Code from figure 11: Analysis of a body sliding down an inclined plane – example code – main.js (1).
var y;
var nstart = 0;
var clickTimer = null;
function startup() {
const el = document.getElementById("okvir_kosihitac");
if (el !== null) {
el.addEventListener("touchstart", tapEvent, false);
el.addEventListener("touchend", handleEnd, true);
el.addEventListener("touchcancel", handleCancel, true);
el.addEventListener("touchmove", handleMove, false); // 3rd parameter passive=false
el.focus();
}
console.log("Initialized.");
y = 0;
}
document.addEventListener("DOMContentLoaded", startup);
Inside the startup() method, which is called when part of the page has loaded and the DOMContentLoaded event fires, as shown in line 19 of figure 11, the events touchStart, touchEnd, touchCancel and touchMove are registered. They fire when the user presses a point on the screen (touchStart), when the touch is interrupted (touchCancel), when the finger moves on the screen (touchMove) and when the touch ends (touchEnd).
Read more about this in the article: developer.mozilla.org/en-US/docs/Web/API/Event/defaultPrevented
Code from figure 12: Analysis of a body sliding down an inclined plane – example code – main.js (2). The methods tapEvent and handleStart
const ongoingTouches = [];
function tapEvent(evt) {
if (clickTimer == null) {
clickTimer = setTimeout(function () {
clickTimer = null;
handleStart(evt);
}, 500);
} else {
clearTimeout(clickTimer);
clickTimer = null;
console.log("double click");
handleDbClick(evt);
}
}
function handleStart(evt) {
console.log("handleStart,defaultPrevented= " + evt.defaultPrevented);
if ((typeof evt.cancelable !== "boolean" || evt.cancelable) && !evt.defaultPrevented) {
evt.preventDefault();
}
console.log("handleStart, after,defaultPrevented= " + evt.defaultPrevented);
// alert('Start');
nstart++;
console.log("touchstart. " + nstart);
const el = document.getElementById("okvir_kosihitac");
const id = el.getAttribute('id');
const processingInstance = Processing.getInstanceById(id);
const touches = evt.changedTouches;
var mx = touches[0].pageX - el.offsetLeft;
var my = touches[0].pageY - el.offsetTop;
console.log('mx=' + mx + ', my=' + my);
processingInstance.touchStart(mx, my);
}
The method tapEvent is called when the user touches the screen once or twice quickly (a double tap). If the object clickTimer is not null, we check whether the time between two taps is less than 500ms (a double tap). If the screen is touched for the first time, this time is certainly more than 500, so the nested function runs, which sets the object clickTimer to null and calls handleStart, which handles a single touch of the screen. On a repeated touch, since clickTimer is now a null object, it is a double tap, and the part of the code under else runs. The code then goes to the function handleDbClick, explained earlier.
The method handleStart gets a TouchEvent object as its parameter, and checks whether the boolean property defaultPrevented is true. If it is not, the method evt.preventDefault() is called, which stops the default behavior when the screen is touched: otherwise mouseClick would also be called, and when the finger is dragged, the page would scroll, the control point would not move and the mouseMove event would not fire. Read more about this in the article: blog.mobiscroll.com/working-with-touch-events/The default handling of events can also be controlled in other ways, with the property cancelable, described in the article: developer.mozilla.org/en-US/docs/Web/API/Event/cancelableThe Canvas element in which the animation, i.e. the Processing code, runs is obtained in line 45 of figure 12 with the method getElementById. Then, in the next line, its id is obtained, and from it the Processing instance in line 47, through which the methods defined in the sketch of Processing can be called.
Through the object evt we get the array of touched points: evt.changedTouches
The coordinates of the touch point are found in lines 49 and 50.
Since the variable touches is an array, its (only) element is touches[0]; pageX gives the x coordinate on the html page, while pageY gives the y coordinate relative to the page. The Canvas element can be moved relative to the page by offsetLeft along x or offsetTop along y.
After the coordinates of the finger's touch relative to the Canvas are computed, the Processing instance calls the method touchStart, explained earlier.
Code from figure 13: Analysis of a body sliding down an inclined plane – example code – main.js (3). The methods handleMove, handleEnd, handleCancel
function handleEnd(evt) {
console.log("handleEnd,defaultPrevented= " + evt.defaultPrevented);
console.log("touchend.");
const el = document.getElementById("okvir_kosihitac");
const id = el.getAttribute('id');
const processingInstance = Processing.getInstanceById(id);
el.focus();
}
function handleCancel(evt) {
// alert('Cancel');
// evt.preventDefault();
console.log("touchcancel.");
el.focus();
y = 0;
}
function handleMove(evt) {
// alert('Move');
console.log("handleMove,defaultPrevented= " + evt.defaultPrevented);
evt.preventDefault();
console.log("touchmove.");
console.log("handleMove after,defaultPrevented= " + evt.defaultPrevented);
const el = document.getElementById("okvir_kosihitac");
const id = el.getAttribute('id');
const processingInstance = Processing.getInstanceById(id);
if (processingInstance.isPritisnuta()) {
const touches = evt.changedTouches;
console.log('x=' + (touches[0].pageX - el.offsetLeft) + ', y=' + (touches[0].pageY - el.offsetTop));
if (y == 0) {
y = touches[0].pageY - el.offsetTop;
}
var dH1 = y - (touches[0].pageY - el.offsetTop);
y = touches[0].pageY - el.offsetTop;
processingInstance.handleMove(dH1);
}
}
Inside the method handleMove, which is called when the user "drags" a finger on the screen of a tablet or mobile device, the Processing instance is first "picked up" in the way already described. Then, through it, we check whether the variable pritisnuta is set to true. Here the getter isPritisnuta() is used.
If it is, the touched points on the canvas are taken from the event object and put into the constant touches (line 81).
If y==0, which is the case at the start, the first value of the y coordinate of the control square is computed; it is used to remember the previous position, only its y coordinate.
Next, the change of the y coordinate between the current and the previous position of the control square M (dH1) is computed.
Then this value is passed as a parameter to the function handleMove defined in the sketch of the application (.pde).
The Processing instance is also picked up inside the handleDbClick() method, and through it the function of the same name defined in the sketch of the application (.pde) is called.
The other functions shown, colorForTouch() and copyTouch(), are not used in this application and can be deleted.
Code from figure 14: Analysis of a body sliding down an inclined plane – example code – main.js (4). The methods handleMove (continued) and handleDbClick
function handleDbClick(evt) {
const el = document.getElementById("okvir_kosihitac");
console.log("double click.");
evt.preventDefault();
console.log("handleDbClick after,defaultPrevented= " + evt.defaultPrevented);
const id = el.getAttribute('id');
const processingInstance = Processing.getInstanceById(id);
processingInstance.handleDbClick();
}
function colorForTouch(touch) {
let r = touch.identifier % 16;
let g = Math.floor(touch.identifier / 3) % 16;
let b = Math.floor(touch.identifier / 7) % 16;
r = r.toString(16); // make it a hex digit
g = g.toString(16); // make it a hex digit
b = b.toString(16); // make it a hex digit
const color = `#${r}${g}${b}`;
return color;
}
function copyTouch({ identifier, pageX, pageY }) {
return { identifier, pageX, pageY };
}
The whole program in one piece (4 pictures joined)
var y;
var nstart = 0;
var clickTimer = null;
function startup() {
const el = document.getElementById("okvir_kosihitac");
if (el !== null) {
el.addEventListener("touchstart", tapEvent, false);
el.addEventListener("touchend", handleEnd, true);
el.addEventListener("touchcancel", handleCancel, true);
el.addEventListener("touchmove", handleMove, false); // 3rd parameter passive=false
el.focus();
}
console.log("Initialized.");
y = 0;
}
document.addEventListener("DOMContentLoaded", startup);
const ongoingTouches = [];
function tapEvent(evt) {
if (clickTimer == null) {
clickTimer = setTimeout(function () {
clickTimer = null;
handleStart(evt);
}, 500);
} else {
clearTimeout(clickTimer);
clickTimer = null;
console.log("double click");
handleDbClick(evt);
}
}
function handleStart(evt) {
console.log("handleStart,defaultPrevented= " + evt.defaultPrevented);
if ((typeof evt.cancelable !== "boolean" || evt.cancelable) && !evt.defaultPrevented) {
evt.preventDefault();
}
console.log("handleStart, after,defaultPrevented= " + evt.defaultPrevented);
// alert('Start');
nstart++;
console.log("touchstart. " + nstart);
const el = document.getElementById("okvir_kosihitac");
const id = el.getAttribute('id');
const processingInstance = Processing.getInstanceById(id);
const touches = evt.changedTouches;
var mx = touches[0].pageX - el.offsetLeft;
var my = touches[0].pageY - el.offsetTop;
console.log('mx=' + mx + ', my=' + my);
processingInstance.touchStart(mx, my);
}
function handleEnd(evt) {
console.log("handleEnd,defaultPrevented= " + evt.defaultPrevented);
console.log("touchend.");
const el = document.getElementById("okvir_kosihitac");
const id = el.getAttribute('id');
const processingInstance = Processing.getInstanceById(id);
el.focus();
}
function handleCancel(evt) {
// alert('Cancel');
// evt.preventDefault();
console.log("touchcancel.");
el.focus();
y = 0;
}
function handleMove(evt) {
// alert('Move');
console.log("handleMove,defaultPrevented= " + evt.defaultPrevented);
evt.preventDefault();
console.log("touchmove.");
console.log("handleMove after,defaultPrevented= " + evt.defaultPrevented);
const el = document.getElementById("okvir_kosihitac");
const id = el.getAttribute('id');
const processingInstance = Processing.getInstanceById(id);
if (processingInstance.isPritisnuta()) {
const touches = evt.changedTouches;
console.log('x=' + (touches[0].pageX - el.offsetLeft) + ', y=' + (touches[0].pageY - el.offsetTop));
if (y == 0) {
y = touches[0].pageY - el.offsetTop;
}
var dH1 = y - (touches[0].pageY - el.offsetTop);
y = touches[0].pageY - el.offsetTop;
processingInstance.handleMove(dH1);
}
}
function handleDbClick(evt) {
const el = document.getElementById("okvir_kosihitac");
console.log("double click.");
evt.preventDefault();
console.log("handleDbClick after,defaultPrevented= " + evt.defaultPrevented);
const id = el.getAttribute('id');
const processingInstance = Processing.getInstanceById(id);
processingInstance.handleDbClick();
}
function colorForTouch(touch) {
let r = touch.identifier % 16;
let g = Math.floor(touch.identifier / 3) % 16;
let b = Math.floor(touch.identifier / 7) % 16;
r = r.toString(16); // make it a hex digit
g = g.toString(16); // make it a hex digit
b = b.toString(16); // make it a hex digit
const color = `#${r}${g}${b}`;
return color;
}
function copyTouch({ identifier, pageX, pageY }) {
return { identifier, pageX, pageY };
}
Check your knowledge
Open the quiz
Quiz: Analysis of a sliding body
1. Why is the body described by a separate class Telo?
2. What changes when the user moves the small square at the top of the inclined plane?
3. How is a touch of the screen caught on mobile devices?
4. What does friction do to a body on an inclined plane?
ANALYSIS OF THE SLIDING OF A BODY DOWN AN INCLINED PLANE - AN EXAMPLE IN PROCESSING
An example should look like the animation below:Click (tap) the small square at the top of the inclined plane and drag it up or down. Double-click or press r to restart.
Description for using the displayed animation:
1) Selecting and deselecting squares. By clicking the mouse (mouseClick event) or pressing the finger (touchStart event) on the square in the corner of the steep plane, it becomes selected and is then colored red. Clicking anywhere on the animation, outside of the square, will deselect it.2) Moving the squares (changing the height of the inclined plane). After selection, the box can be moved in several ways depending on the device: On a desktop computer or tablet, if a mouse is used, it can be dragged (mouseDragged) along the Y axis and change the position and thus the height of the inclined plane, or once click above or below the previous square position. If keyboard operation is supported, clicking the UP or DOWN arrows can also change the height of H, the inclined plane.
On mobile devices and tablets, the square can be moved after selection with the finger (touchMove event).
As the position of the square changes, the height H of the inclined plane changes, as does the slope. In the default position, for defined sizes:
gde je
coefficient of friction μ = 0,2 i
mass m = 1kg
friction force Ftr = μ * N;
does not allow the body to move, because for the initial angle of α = 4,o
obtained by the formula
α = atan(H/L);
the force of gravity along the inclined plane is not large enough to overcome the force of friction
gde je Fa component of the force of gravity along an inclined plane
4) Printing the text. In order to draw text, it is first necessary to create a font f(PFont). Then the textFont(f) method (from the basic processing library) should be used to set the previously created font, passing it as a parameter to the textFont() method. In the end, printing is also done using the processing method text(textForPrinting, x,y) , where the text to be printed and the position of that text on the screen, given by the sent coordinates x and y, are passed as parameters.
Code analysis
Since the PShape object and everything related to drawing shapes in this way is not supported in javascript, this had to be done in another way, which will be shown in the following images. The old code is only commented out so that it can be distinguished with the new code. In the case of using the application on desktop computers, PShape can be used. Let's first look at the changes in the SlidingBody class, which are shown in the image below:
processing.org/reference/beginShape_.htmlIn the main part of scatch the variables are declared: angle of inclination of the inclined plane fi, vectors of position, velocity v, acceleration a, component of the force of the weight of the body along the inclined plane Tx, Normal force with which the body acts on the base N, resultant force Fr, mass m and coefficient friction. In the constructor, vectors are created to the end and initial values are set with components whose intensities are equal to zero.
.
The move() method defines changes in acceleration, velocity and position of the body between two calls to the draw() method, i.e. every 1/NUMBER_OF_FRAMES seconds.
The change in acceleration is caused by the change in the resultant force, which causes this acceleration: a=PVector.div(Fr/m) i.e. (a=Fr/m - 2nd Newton's law).
Since the measurements are in px and not in meters, scale is used to make the animation more realistic.
A change in acceleration further causes a change in velocity, and a change in velocity causes a further change in position, the calculation of which can be seen in the continuation of the move() method.
the boundaryConditions() method has not been changed in relation to the basic variant of the task.
The reset() method returns the physical sizes to their initial values, as they were defined in the constructor.
The main part of scatch can be seen in Figures 4-11.
They are further defined: angle of inclination-angle (error, this line should be deleted), sliding body-slidingBody, w and h are the width and height of the body, fi-angle of inclination of the inclined plane in radians.
The logical variables stop and pressed tell about whether the body has reached the bottom of the inclined plane and the animation is stopped, while the variable pressed refers to the selection of the control point (square M), whether it is selected or not. Once selected, it can be moved by dragging the mouse, up or down, thereby increasing or decreasing the height of the inclined plane.
The constants G, SCALE and NUMBER_OF_FRAMES define the gravity constant, scale(px/m) and the number of frames per second, respectively.
The variables f, event and pY are also defined. The variable f is used to define the font to print the text on the screen. The string variable event displays the type of event (eg mouseClick), which is displayed as text on the animation (see below in Figure 6).
The variable pY stores the previous value for the Y coordinate of the position of the control point M.
Figure 4 shows part of the setup() method. This part is explained in the basic version of the animation.
Then the font f is created, the text for the event display is defined, and the initial value of the y coordinate where the body is located is calculated.
Inside the draw() method, after setting the background color and the fill color, the beginning of beginShape(TRIANGLE_STRIP) can be seen. This will create and plot the ground. This is further shown below (Figure 6).
The indicators TRIANGLE_STRIP and QUAD indicate that the area of the triangle (ground) and square (M) is obtained by joining consecutive right triangles and squares, respectively.
Before drawing the square M, the coordinate system was translated from the upper left corner of the screen to the top of the ground, i.e. for the value height-H-h/2.
This means that the coordinates for drawing the check box points are now measured in the new coordinate system. These changes will be used to draw the square, but the state will return to the old state after that, because this code is written between pushMatrix() and popMatrix().
Read more about it in the article:processing.org/reference/pushMatrix_.html
The preparation refers to the rotation of the coordinate system by the angle fi, and then the methods defined in the body class are called in order: forces(), move(), boundaryConditions(). These methods have been explained earlier.
Before drawing the body, by calling the render() method, the coordinate system, in addition to the previous rotation, is now additionally translated to the position above the top of the ground, at the beginning of the oblique plane, from where the body will actually start moving, i.e. to slide along that plane.
After drawing the body, the coordinate system is returned to the old one, and then the text is printed on the screen, by calls to the text() method. Using the text method and setting the font is described in the article processing.org/reference/text_.htmlFinally, the value of the logical variable stop is checked. If it was previously set to true within the boundaryConditions() method, it is a sign that the body has reached the base of the steep plane and then the animation loop is stopped and the values of the physical quantities are set to their initial values, within the reset() method, which is called from here.
Read more about it in the article:developer.mozilla.org/en-US/docs/Web/API/Touch_eventsPart of the javascript code will be shown at the end of this article.
The handleMove(float dH) method is called from the mentioned javascript. It changes the height of the steep plane by the dH value that is passed as a parameter to this method, and is also determined within javascript.
The handleDbClick() method is a handler method that is called from javascript when the user quickly clicks 2 times in a row. and does the same as the reset() method which is called when the user presses the 'r' key on the keyboard.
Javascript code in the application that describes the animation of a body sliding down an inclined plane: "InclinedPlaneObject"
The Javascript code is located in the main.js file and is shown in parts in Figures 11-14.
The handleStart method receives a TouchEvent object as a parameter and checks whether the logical variable defaultPrevented is equal to true. If not, the evt.defaultPrevented() method is called, which will prevent the default behavior when touching the screen, which means that mouseClick will also be called, and when the finger is dragged, the page will scroll and the control point will not move and the mouseMove event will not be fired. Read more about it in the article: blog.mobiscroll.com/working-with-touch-events/Podrazumevano pozivanje događaja se može regulisati i na druge načine, pomoću osobine cancelable, što se opisuje u članku: developer.mozilla.org/en-US/docs/Web/API/Event/cancelableCanvas element u kome se izvršava animacija tj. processing kod se dobija u redu 45 na slici 12, metodom getElementById. Zatim se u sledećem redu dobije sam id i na osnovu njega processing instanca u redu 47, pomoću koje se mogu pozivati metode definisane u scatch-u processing-a.
Pomoću objekta evt se dobije niz prethodno dodirnutih tačaka: evt.changedTouches
Koordinate tačke dodira se određuju u linijama 49 i 50.
S obzirom da je promenljiva touches niz, član niza(jedini) je touches[0], a pageX daje koordinatu x na html stranici, dok PageY daje y koordinatu u odnosu na stranicu. Canvas element može biti pomeren po x osi u odnosu na stranicu za veličinu OffsetLeft po x ili OffsetTop po y osi.
Posle izračunavanja koordinata dodira prsta u odnosu na Canvas, pomoću processing instance se poziva metoda touchStart, koja je ranije objašnjena.
If it is, the previously touched points on the canvas are taken from the event object and placed in the touches constant (line 81).
If y==0 which is the case at the beginning, the first value of the y coordinate of the check box is calculated, which is used to remember the previous position and only the y coordinate.
Below, the change in the y coordinate between the current and previous position of the check box M(dH1) is calculated.
Then that value is used as a parameter and passed to the called handleMove function defined in the application's scatch(.pde).
Processing's instance is also downloaded within the handleDbClick() method, and the function of the same name defined in the application scatch (.pde) is called via that instance.
The other shown functions colorForTouch() and copyTouch() are not used in this application and can be deleted.
