1 of 70

OBJECT ORIENTED PROGRAMMING

2 of 70

Ishan, interested in planetary science, sought help from his father to visually represent his ideas about the solar system. His father helped him visualise his ideas. Can we also assist him?

3 of 70

This project emphasizes the learning of Object Oriented Programming and p5js in which we will build a web that showcases the planets in our solar system.

4 of 70

  • To learn about the 3d view of objects on a website.

  • To gain knowledge about Object Oriented Programming.

  • To explore about p5js and the WebGL mode of p5js.

5 of 70

  • Books have always been a great knowledge-gaining source.
  • Dictionaries came into existence to understand the words or the things that we don’t know. This resulted in the creation of an Encyclopedia.
  • An Encyclopedia is a comprehensive reference book with detailed information for gaining knowledge of various things all around the world.
  • It usually consists of high-resolution images to support detailed information.
  • Image Credits: Britannica.com

6 of 70

  • Nowadays, we can have all such information on computers via applications and websites.
  • Websites keep the audience engaged by using high-resolution images, videos, audio, and interactive elements.
  • For example, we can explore the National Geographic Kids Website, which is full of Images and videos.

https://kids.nationalgeographic.com/

  • Image Credits: Britannica.com

7 of 70

  • Modern websites also exhibit 3D models and animations, along with 2D images, for a better understanding of concepts and user experience.
  • Interactive elements like 3D objects, that users can move or rotate to get a 360-degree detailed perspective, enhance user experience.
  • Such visually rich content provides a comprehensive understanding and better learning experience.

8 of 70

When we click on the button, we will see a 3D model of a dog in augmented reality that we can zoom in, zoom out, or rotate to observe from any angle.

For example, if we search for a ‘dog’ or any animal in the Google search on a smartphone, we can see an option, ‘View in 3D’.

9 of 70

  • Similarly, another example is ‘Google Earth’ where we can see the Earth in 3D, and rotate or zoom it using the mouse to see the different parts of the Earth.
  • Check the 3D model of the Earth on the website https://earth.google.com/.

10 of 70

Programming and Real World

  • Programming applications help us in a variety of ways in our daily lives to make life easier. Hence, programming languages are inspired by the design of the world around us.
  • For example, we have objects everywhere around us with names and properties; each object may perform certain tasks, and so on.
  • Similarly, we can create data entities to store data called ‘objects’ that can have properties and functionalities. This approach in coding is called Object-Oriented Programming (OOP).
  • As we move forward, we develop more complicated and real-time applications. Here, Object-Oriented Programming comes into the picture, which helps in the processing of complex data.

11 of 70

In this lesson, we will create a web platform using p5js that will display planets in our solar system.

12 of 70

We will use a 3D platform and also include interactive elements to enhance the user experience.

A rough user Interface

13 of 70

Open p5js

One of the planets nearest to the Earth is ‘Mars’, also known as the ‘Red Planet’. It is mostly reddish-orange in colour.

Step 1: Open the p5js editor

14 of 70

Step 1: Change the ‘canvas size’ to ‘500x500 pixels’ and the ‘background colour’ to ‘black’.

  • Draw a circle at the center of the canvas of ‘300 pixels’ diameter and a colour like that of Mars.

Draw mars

15 of 70

  • We can see a dark orange coloured circle that represents Mars. To make it more realistic, instead of 2D, we can add a 3D object to display the Mars planet.
  • p5.js is a powerful tool for creating 2D graphics and by default, the canvas is in the ‘P2D’ mode for rendering in 2D.
  • It also offers the ability to render 3D graphics using the ‘WEBGL’ library, which enables the third dimension, ‘Z’, within a web browser.

16 of 70

  • Creating 3D designs can be difficult since we need to add features such as shape, texture, and lighting to the 3D models.

  • Computers contain a particular element called the Graphics Processing Unit.

  • (GPU) that handles the complex calculations required to render such 3D models.

  • The GPU can operate on multiple tasks at once when we are dealing with pixels and various shapes in 3D space.

17 of 70

  • WEBGL library provides a 3D rendering technique in p5js that allows us to display 3D shapes and objects with features such as lighting, texture, and viewing camera angle.
  • We can enable the 3D mode by adding the keyword ‘WEBGL’ in the ‘createCanvas()’ command as the third parameter.

Syntax: createCanvas(width, height, WEBGL)

18 of 70

  • When drawing in 2D, the point (0,0) is located at the top left corner of the screen. However, in the ‘WebGL’ mode, the origin of the sketch (0,0,0) is in the centre of the screen.
  • By default, the x-axis moves left to right, the y-axis moves up to down, and the z-axis moves from further to closer.

19 of 70

  • Now, with these fundamentals in place, we can add 3D objects. There are many basic shapes that we can draw using simple commands in p5js.

20 of 70

For adding a planet, we can use a ‘sphere’ shape. sphere() – This command draws a sphere with the given radius. Add a sphere instead of a circle using the ‘sphere()’ command.

Step 2: Add the keyword ‘WEBGL’ in the ‘createCanvas()’ method as a third parameter. Add a comma before the ‘WEBGL’ keyword.

  • Comment out the ‘circle()’ command and replace it with the ‘sphere()’ command with a ‘150 pixels’radius as an input parameter.

Draw mars

21 of 70

  • We can see a sphere with some geometrical lines. We can make it look realistic by removing the geometrical lines and using hues that resemble the surface aesthetics of Mars.
  • For example, the tint of the sphere is quite like the colour of the Mar’s surface. We can also add a few shapes and patches to make it look more like Mars.
  • However visuals of actual mars’s surface include craters and patterns with incredibly complicated hues of varied colours.

22 of 70

  • Texture refers to the visual and tactile characteristics of the surface. It is similar to a ‘skin’ that wraps around a 3D geometry. Even though the surface details are not there in 3 dimensions, texture makes it appear to have them. For example, uneven surfaces or craters on the Mars.

  • Images and video are the only textures that are currently supported.

  • We can use digital images of texture to replicate the appearance of different materials, such as wood, metal, fabric, or any surface.

23 of 70

  • The complex visual properties applied through textures give a detailed and realistic look to the 3D models.
  • In this case, we can use the following image as the texture of the Mars surface.

24 of 70

  • We can download the image from a folder with the texture of various planets using the QR Code or link.

https://trendsettersindia my.sharepoint.com/:f:/g/personal/chinmay_dharmadhikari_ict360_com/ErYlV5vK_hJLhNSVjYwGxlUB6a2koAehQNHu9QswNkRFSA?e=lh5j1g

Draw mars

25 of 70

Step 1: Upload the texture image provided in the resources to the ‘Sketch Files’ section.

Add Texture

26 of 70

  • We will be able to see the image ‘mars.jpg’ in ‘Sketch Files’.
  • To remove the geometrical lines and apply texture on the surface, we can load the image in the code and use the ‘texture()’ and ‘normalMaterial()’ commands respectively.
  • normalMaterial()

This command sets the current material as a normal material. It is not affected by light.

  • texture()

This command sets the input image or video as the texture to render subsequent shapes.

27 of 70

Step 2: Add a new preload function that will load the image into a variable at the beginning of code Execution.

Now we can see that the texture image is wrapped over the sphere to make it look realistic.

Add Texture

  1. Add the ‘loadImage()’ command with the path to the image as an input and assign it to the ‘Mars Image’ variable ‘marsImg’ to save the image in a variable in the ‘preload’ function.
  2. Add the ‘normalMaterial()’ command before the ‘sphere()’ command to remove the geometrical lines from the sphere in draw().
  3. Add the ‘texture()’ command and add an image ‘marsImg’ as an input to add texture to the sphere after normalMaterial() command.

28 of 70

  • We will move the sphere upwards to make room underneath to show the planet information later.

  • We can use translate() for the same purpose.

  • translate() shifts the origin by given dimensions. It accepts arguments for (x,y) or (x,y,z) values to modify the translation along each axis.

  • Everything we draw after calling translate() will be positioned relative to that point.

29 of 70

  • We can also add rotation animation to the sphere object so that the user can see all parts of the planet while it rotates around its own axis.

  • To rotate the sphere along the y-axis, we can use the ‘rotateY()’ command before the ‘sphere()’ command. However, we need to give a constant linearly increasing number as an angle input to the ‘rotate’ command.

  • We can either create a counter or use the ‘millis()’ method.

30 of 70

  • Millis(): The ‘Millis’ method returns the number of milliseconds (thousandths of a second) since starting the code execution, i.e., when setup() was called.

  • We can use the ‘millis()’ command as an input to the ‘rotate’ command. However, the output value of the ‘millis()’ increases rapidly.

  • This can be checked using a console. Therefore, we can reduce the speed by dividing ‘millis()’ by ‘100’ and using it as an input to the ‘rotateY()’ command.

31 of 70

Step 1: Use the ‘rotateY()’ method with ‘millis()/100’ as an input. Add the ‘angleMode(DEGREES)’ command in setup to consider the input values in degrees instead of radians.

We can see that Mars is rotating around its own axis. This looks realistic and engaging compared to any 2D image.

Add Rotation to 3D Object

  1. Add the ‘translate(0,-50)’ command before rotate() to move the sphere upwards.
  2. Encapsulate code related to a sphere using the ‘push()’ and ‘pop()’ methods to apply changes exclusively to the Mars sphere.

32 of 70

Display Information

  • Now that the 3D model is ready, we can display planet’s information, such as name, diameter, number of moons, distance from the sun, and gravitational force.

Planet Name

Diameter (km)

Number of moons

Gravity (m/s2)

Length of a day

Mercury

4,879

0

3.7

59 days

Venus

12,104

0

8.9

243 days

Earth

12,760

1

9.8

24 hours

Mars

6,792

2

3.7

24 hrs 37 min

Jupiter

1,42,984

92

23.1

9 hr 55 min

Saturn

1,20,536

146

9.0

10 hr 40 min

Uranus

51,118

27

8.7

16 hr 50 min

Neptune

49,528

14

11.0

6 hr 11 min

33 of 70

  • The planet’s values are subject to change, though taken from an authentic source from the NASA website, as continuous research results in changes.
  • For simplicity, we will add only two properties— ‘name’ and ‘diameter’. We will use variables to save this data.

34 of 70

Create variables for displaying information

Step 1: Create new variables ‘name’ and ‘dia’ to store the name and the diameter of the planet, respectively.

  • Initialize the variables in setup()

‘name’ as “Mars” and ‘dia’ - “6,792 km”.

Create Variables

  • The value inside the ‘dia’ variable is a string and not a ‘number’ datatype.

35 of 70

  • In p5.js, we use the ‘text()’ command to display text on the screen.
  • We can customize the font and size of the text. By default, p5.js uses a standard font for the text.
  • However, when using the WebGL mode, we can only use fonts that have been loaded using the ‘loadFont()’ method.
  • This means we need to upload a font file in the ‘.tff’ format and include it in our code.
  • In this session, we will use a font called ‘Kanit-Bold’, which can be found in the resources folder shared with you through a QR code.

36 of 70

Step 1: Download the ‘Kanit-Bold.tff’ file from the resources folder shared earlier using QR code.

Upload the file in the p5js editor sketch files.

  • Declare a variable ‘f’ at the beginning. Use the ‘loadFont()’ command to load the ‘Kanit-Bold.tff’ font and assign it to the ‘f’ variable in the ‘preload()’ function

Add Information Text

37 of 70

Now, we will start adding the code to display text after the code is added to display Mars in 3D.

  1. Add the ‘fill(255)’ command to fill the text with white colour.
  2. Note that when text is added, it is considered as a shape that has a border and a fill area inside.
  3. Use the ‘textSize()’ command and set it to ‘20’. Try changing the size later when the text is displayed.
  4. Use the ‘textFont()’ command and set it to the ‘f’ variable to have the ‘Kanit-Bold’ font.
  5. Use the ‘textAlign(CENTER)’ command to align text centrally.
  6. Use the ‘text()’ command to display the name and diameter in the format ‘property_Name : property_Value’ just below the sphere

38 of 70

  • Now, we can observe Mars with realistic texture in 3D and its properties.
  • We can also display more properties or information, if required.
  • This approach to learning about planets is much more engaging and informative than conventional methods.

39 of 70

  • We have been using variables to save and display different information about planets. However, if we want to show more details, we will need even more variables, which can make the code long and difficult to manage.
  • Plus, if we want to show information about many planets, we will need even more variables.
  • This is when arrays can be helpful. Arrays allow us to organise information together.
  • For instance, if we want to display details about planets such as Mars, Earth, and Jupiter, we can create arrays for their names, diameters, and any other information we want to show.

Var names = [“Mars”,“Earth”,“Jupiter”];

var dia = [“6792 km”,“12,760 km”,“1,42,984 km”]

40 of 70

  • When it comes to multiple properties of the planets, we will have to use multiple arrays.

  • We must create separate arrays to display different properties. Also, each array must have the same order of elements as the sequence of planets.

  • All of this complicates the code. However, we can make things easier by using Object-Oriented Programming.

  • This approach both simplifies the code and makes it more organized.

41 of 70

What is OOP?

  • In real life, we interact with various objects around us. For example, we eat food on a plate with a spoon.
  • In this process, food, plate, spoon, and the person eating all interact with each other in a certain way.
  • Each object has its own properties and functions, such as the plate, which is usually flat and can contain food. The spoon, which can be held with a hand, is used to pick up a bite and put it in the mouth.

42 of 70

  • Similarly, the entire world around us comprises objects that interact with ourselves and with one another.

  • As programming is mainly used to create real-world applications, the same concept is used in programming called ‘Object-Oriented Programming’.

  • This concept simplifies the development of real-world applications.

  • Generally, objects having similar properties are classified in a group or class. For example, ‘animal’ is a class with several elements such as human, cat, dog, tiger, elephant, etc

43 of 70

  • Consider another example of the dog as a class.
  • Its objects can be different dogs with properties such as name, breed, colour, and functions like walking, barking, running, etc. Similarly, in OOPs, we can create a class with common properties and methods.
  • Multiple objects can be created from a class that can have common property types.

44 of 70

  • Another example is, In coding, we use many entities that we represent using variables.
  • For example, if we are creating a game that has Pokémon, there will be several Pokemon with different properties and actions. We can create a class ‘Pokemon’.
  • We can create multiple objects from the class ‘Pokemon’ like Pikachu, and associate them with all the property variables and functionality methods of the class with the object.

45 of 70

  • In object-oriented programming, multiple variables of different data types and methods are associated with a single object. This makes programming much simpler and code easy to manage.

  • Object-Oriented Programming (OOP) – This is a programming paradigm that organizes code based on the concept of objects, each of which can have its own data (attributes) and behaviours (methods).

  • We can use those objects in programs that can interact with users as well as among themselves to build complex software systems. This approach in programming is known as ‘Object-Oriented Programming’.

46 of 70

Example

  • We are creating a platform that will display planets and their information.

  • The code we have is a procedural structure with variables for properties such as name and diameter.

  • However, if we want to show multiple planets, we can create an object of planets that stores the properties and methods of each planet.

47 of 70

Object – An Object is a unique data entity that can contain the properties and methods. Objects can be created independently, similar to defining a variable, or they can be created from a class. If the object is created using a class, then it is termed an ‘instance of a class’.

  • If the object is created using a class, then it can also be termed as an ‘instance of a class’.

Example

A ‘car’ is a real-life Object, which has some characteristics like colour, type, and model, and performs certain actions like driving.

48 of 70

  • The characteristics of an Object are called ‘Property’ and the actions are called ‘Methods in Object-Oriented Programming’.

What properties can we identify of the planet in the code we created earlier?

  • We can review the code and identify properties such as– name, diameter, and path of the texture image associated with the planet object.

49 of 70

Object Literal

  • Objects can be created independently using ‘Object Literal’ in JavaScript. ‘
  • Object Literal’ is a comma-separated list of name-value pairs inside curly braces.
  • The syntax to create objects has curly brackets {…} with a list of properties separated by commas.
  • A property is a ‘key: value’ pair, where a key is a property name, and the value can be anything.

50 of 70

Following are the syntax rules:

  • A colon separates the property name from the value.
  • A comma separates each name-value pair from the next.
  • A comma after the last name-value pair is optional.

51 of 70

  • If any of the syntax rules are broken, such as a missing comma or colon or curly bracket, an error will be generated.
  • For example: if we want to create an object for Mars planet, we can have property variables such as name, diameter, and image path. We can create an object ‘Mars’ as follows.

var mars = {

imgPath : “mars.jpg”,

name : “Mars”,

dia : “6,787 km”,

};

52 of 70

  • The individual property of an object can be accessed using the object name and key joined with a ‘dot (.)’ operator. For example, to access the value of the ‘imgPath’ property of the object, we can write,

‘mars.imgPath’.

  • Use the console with the ‘console.log(mars.imgPath)’ command and check the output. Similarly, we can check values in other properties.

53 of 70

Implement the concept of an object into code.

Step 1: Comment out or remove the variable declaration and initialization in the setup.

  • Create an object ‘Mars’ with properties ‘imagePath’, ‘name’, and ‘dia’ at the beginning of the code.

Create mars object

54 of 70

Note that we had created the ‘marsImg’ variable to store the texture image of the mars.

  • In the object, we did not create a property to store the image. Instead, we added a ‘String’ property to store the image path.
  • We can also add a new object property or update the existing one directly using the ‘dot (.)’ notation.
  • We can create the new object property as ‘mars.img’ instead of the ‘marsImg’ variable.
  • Replace the ‘marsImg’ variable by creating the new object property ‘mars.img’ in the ‘preload’ function.

55 of 70

  • Replace the ‘marsImg’ variable by creating the new object property ‘mars.img’ in the ‘preload’ function.

  • Use the object and its property ‘mars.imgPath’ instead of the ‘imgPath’ variable in the ‘preload’ function.

  • Use the console to check the contents and the new ‘img’ property in the ‘mars’ object using the ‘console.log()’ command.

Add image object property

56 of 70

Update the code with the object properties

Update the ‘marsImg’ variable in the rest of the code with the ‘mars.img’ object property in the ‘texture()’ command.

Also, update the variables ‘name’ and ‘dia’ with the object properties ‘mars.name’ and ‘mars.dia’ in the text command, respectively

Now we can see the same result as earlier, with a rotating Mars sphere and basic information displayed at the bottom.

We can also add and display more properties from the table.

Update the code

57 of 70

To add more planets, we need to create multiple objects.

For example, to add the Earth we can create a new object as we did earlier. Instead of creating multiple objects, we can create an array of objects.

Array of Objects: Just like a normal data array, we can create an array of objects. Each object in an array is identified by an index number that represents its position in the array. In arrays, the first element index in the array is [0], the second element index is [1], and so on.

We can create an array by adding objects in place of data separated by commas. In this activity, we can create an array of objects for planets.

58 of 70

  • To access a specific property of an object, we can first get an object from the array using the ‘index’ and then use the ‘dot (.)’ notation.

For example, ‘planets[1].name’ will have value as ‘Earth’. We can check other properties using the console.

  • Let us implement this to add more planets.

59 of 70

Step 1: Add an ‘Earth’ texture image from the resources in the Sketch Files.

  • Create an array of objects called ‘planets’ with properties such as ‘imgPath’, ‘name’, and ‘dia’. Use values from the table.

Add multiple Planets

60 of 70

  • Note that we have added a property that stores the texture image in the ‘preload’ function.
  • As we have multiple elements in the array, we will use a ‘for’ loop to iterate through all the objects in the array and add the ‘img’ property using the ‘loadImage()’ command and ‘image path’.

61 of 70

Adding texture image for all objects in the array

Step 2: Comment out the code to add a texture image for Mars in the ‘preload()’ function.

  • Add a ‘for’ loop with counter ‘i’ starting from ‘0’; with condition ‘i’ less than the length of the planet’s array element and incrementing the loop by ‘1’ with each iteration.
  • Add code to create the new ‘img’ property for each object planets[i] in an array and assign thetexture image using the ‘loadImage()’ command with image path - ‘planets[i].imgPath’ for each planet.

Add multiple Planets

62 of 70

Now, we have data and image files that can display multiple planets.

However, at a time, we can show only one planet with the proper size on the screen.

In this case, we can use a key to display the next planet and its information in the same position as a carousel.

Create counter for planet to be displayed

Step 3: Declare a variable ‘count’ at the beginning and initialize it to ‘0’ in the setup.

Add multiple Planets

63 of 70

Add functionality to change the planet

Step 4: Update the object as ‘planets[count]’ from ‘Mars’ throughout the code i.e., in texture and text commands.

Now, based on the value of the ‘count’ variable, the planet from the array will be displayed.

  • Add the function ‘keyPressed()’ to detect the key press event.
  • Add the ‘if’ conditions to detect if the default variable keycode is ‘RIGHT_ARROW’ or ‘LEFT_ARROW’ to detect which key is pressed and increment or decrement the ‘count’ variable, respectively.

Add multiple Planets

64 of 70

  • We can change the planet displayed on the screen by pressing the left or right arrow keys.
  • We have just added only two planets to our array so far (present at locations ‘0’ and ‘1’). Therefore, if the ‘count’ is ‘less than 0’ or ‘greater than 1’, then an error will be displayed.
  • To address this issue, we can add conditions so that the ‘count’ value will be updated cyclically and always be equal to the index values available in the array. This will create a carousel like functionality.

65 of 70

Step 1: Add the ‘if ()’ statement to check the condition > ‘count < 0’. If the condition is ‘true’, set the ‘count’ value as the index of the last object in the array i.e., (planets.length – 1).

This way, we will have a cyclic counter. If the first planet is displayed and the ‘left arrow’ key is pressed, the last planet will be displayed on the array list.

  1. Below the ‘if()’ statement, add the ‘else if()’ statement to check the condition > ‘count == planets.length’ i.e., if the counter moves to the next value from the index of the last index available in the array.
  2. Since the index of the last object element in an array is always (planets.length – 1) and no array object will be available at the index (planets.length), we can go to the first planet from the last one. Therefore, if the condition is ‘true’, set the ‘count’ value to ‘0’.

Circular Switching through array

66 of 70

With this code, the entire application is ready. We can now use arrow keys to go through the planets shown in 3D with their details. This type of interactive 3D application is the future of Digital Encyclopedia.

67 of 70

68 of 70

  • What is OOP?

  • What is WEBGL mode in p5js?

  • What is the purpose of the command normalMaterial():?

69 of 70

Update the code to include more planets and celestial objects with their detailed information data.

70 of 70