Download presentation
Presentation is loading. Please wait.
Published byTodd Newton Modified over 9 years ago
1
Chapter 6 – Interacting Objects: Newton’s Lab
2
topics: objects interacting with each other, using helper classes, using classes from the Java library concepts: collection, list, for-each loop, standard class library In this chapter, we shall investigate more sophisticated interactions between objects in a world. As a start, we shall investigate one of the most universal interactions between objects anywhere: Gravity.
3
Newton’s lab
4
Objects in Space The only non-abstract Actor-subclass of this scenario What kinds of bodies are in our solar system? Why don’t we see a “Sun” class? Why no “Planet” class? Open the Newtons-Lab-1 scenario from the book- scenarios folder. You will see that a world subclass already exists (called Space). We also have classes SmoothMover, Body, and Vector
5
Solar System The types of bodies in our solar system include planets, planetoids, moons, asteroids and comets. For our purposes we will consider each body only with regard to its color, size, mass, and the characteristics of its movement. This means that we can use abstraction to implement ONE class to handle every type of body.
6
The Space class: - 3 configurations of Space What happens when you activate one of these methods? Right-click on the Space world background
7
Space Public Methods Constructors within Constructors ?
8
Inspecting Body Methods Right – click on a body. What methods does it have?
9
Inspecting Body Properties Right click on a planet and inspect its properties. How does the object store its position?
10
Inspecting Body Properties Each Body holds a Vector object. What does the Vector object represent?
11
Helper Classes 2 Support Classes - SmoothMover - Vector SmoothMover is an Abstract class. Abstract classes do not have constructors. We will never place a “SmoothMover” on the board.
12
Helper Classes for Import Edit Menu / Import Class… Some Helper Classes Animal Counter GifImage Label Map Plotter ScoreBoard SimpleTimer SmoothMover Weather
13
More Helper (or Support) Classes http://www.greenfoot.org/doc/support_classes Some Helper Classes AnimatedActor Counter Explosion FPS GifActor MidiPlayer Mover Plotter Rotator Slider
14
The SmoothMover Class A SmoothMover is an Object that stores and calculates its position as decimal numbers instead of integers. This allows for “smoother” and more precise movement. Each SmoothMover stores its movement as a Vector object. A Vector object stores direction and speed of movement.
15
Methods Inherited from SmoothMover SmoothMover objects have the same method (setLocation) twice. How do they differ? Why are they necessary?
16
Vectors Cartesian Representation: Two offsets (dx, dy) that determine how the position changes on a Cartesian Plane. Polar Representation: Change in position is defined by a direction and how far in that direction we move.
17
Vector Class Variables The Vector class implements BOTH Polar and Cartesian representation. All necessary conversions are handled within the class.
18
Method Inheritance Open and read SmoothMover and Vector. Which methods can we actually execute from the object menu? Every SmoothMover holds a Vector. Why can we not call Vectors methods from the menu?
19
Constructors A Constructor has no Return Type Specified A Constructor Always has the Same Name as the Class Constructor is Automatically Executed whenever an Instance (or object) of the Class is Created
20
Default Constructors Does not have any parameters. Makes it easy to create bodies interactively without having to specify details. This is a default constructor. What about the second constructor?
21
Default and non-Default Constructors The Body class has 2 constructors with different parameters. We call this an overloaded constructor Methods can have the same name, as long as their parameters are different. This means that the methods (or constructors) have different signatures.
22
this() and this. Invokes the non-default constructor with the specified values. There are two version of the variable “mass” in existence at this time. The Parameter “mass” and the class attribute “mass”. The “this.” means that we are assigning the value of the Parameter to the attribute and NOT the other way around.
23
Constants Means the value cannot be changed. Means it’s shared between all instances of this class. These variables are called constants. These variables do not change in a program.
24
Change act() so that it moves without applying any forces
25
Body Behavior Create multiple bodies. How do they behave?
26
Add Movement (Left) How would you make the body move left?
27
How to make objects go left? 0 360 -270 90 -90 270 -180 180
28
/** * Construct a Body with default size, mass, movement and color. */ public Body() { this (20, 300, new Vector(180, 1.0), defaultColor); } Change the Direction in the Default Constructor from 0 to 180 Solution: Left Movement
29
Java Packages Programmers typically use packages to organize classes belonging to the same category or providing similar functionality. We can have a look at all the premade packages/classes of Java by selecting “Java Library Documentation” from the “Help”-tab. Imported using dot notation. import java.awt.Color;
30
Importing Java Color Library
31
For example, every color is represented as a mixture of the three additive primary colors Red, Green, and Blue Each color is represented by three numbers between 0 and 255 that collectively are called an RGB value Representing Color
32
Color is expressed as an RGB (red-green-blue) value because our eyes have three types of color receptors that respond to light that has some amount of one of those three primary colors in it. The mixture of the different amounts of those three colors creates different colors. An RGB value of (255, 255, 0) maximizes the contribution of red and green, and minimizes the contribution of blue, which results in a bright yellow RGB Color Combinations
33
A color in a Java program is represented as an object of the Color class The Color class also contains several predefined colors, including the following: The Color class
34
Other Predefined Colors: The Color class
35
You can define Custom Colors by declaring your own Color object with different RGB values as follows, where r,g,b are 3 values from 0 to 255: Color theColor = new Color(r,g,b); The above statement declares “theColor” to be an object variable (instead of a primitive variable) with Color as its type. The term “new” means that a new instance of the object will be created with the specified values. Custom Colors
36
Default Color of Body Calls the Color class. Sets the RBG values What is the legal range for colors?
37
Adding Gravitational Force
38
Apply Force To Do List To apply forces from all other Bodies to a Body, we will: a) Create a list containing all the Bodies currently in Space And b) Go through the list and apply the gravitational force of each of these bodies in sequence
39
Apply Force Algorithm Apply forces from other bodies: get all other bodies in space; for each of those bodies: { apply gravity from that body to our own; {
40
Apply Force – Part I Methods (and Variables) only intended to be called from within the class can be labeled private. When methods are intended to be called from outside the class, they should be labeled public.
41
Greenfoot World Methods http://www.greenfoot.org/files/javadoc/greenfoot/World.html Which methods give us access to objects within the world? We can have a look at all the Greenfoot-specific classes by selecting “Greenfoot Class Documentation” from the “Help”- tab.
42
Getting Objects (World Methods) getObjects(java.lang.Class cls) Gets a list of all objects in the world of a particular class. getObjects(Body.class) Gets a list of all objects of class Body in the world. getObjects(null) Keyword null is a special expression that means no object. This call will get a list of ALL object in the world.
43
Getting the Body Objects World getWorld() There is a method in the Actor class that gives us access to the World class. It signature is World getWorld() This method allows you to get access to all objects that have been added to your World. getWorld().getObjects(Body.class) Can be used from an actor to get all objects of class Body. It returns a java.util.List object. What is that?
44
Java.util.list What methods can be used to add items to a list? What methods can be used to remove items to a list? What methods can be used to find out how many items are in a list?
45
Lists can contain different types (or classes) of objects This notation tells us that a List is a generic type. Meaning a List has no data type itself. We provide the Data type by specifying it in the bracket. List …
46
Apply Force – Part II
47
For-Each Loops Helps to step through the items in a list. for (Type variableName : list) { statements; } You identify the variable type and name, then on the other side of the colon, you identify the list of values. Then the loop goes through the statements for each value in the list, using the variableName as an identifier for the object currently “in use”.
48
Apply Force – Part III Use an if-statement so that gravity is applied from all objects (bodies) in the list except the current object. “this” refers to the current object.
49
Applying Gravity
50
Apply Force Algorithm Apply forces from other bodies: get all other bodies in space; for each of those bodies: { apply gravity from that body to our own; {
51
Newton’s Law Newton's Law of Universal Gravitation states that every massive particle in the universe attracts every other massive particle with a force which is directly proportional to the product of their masses and inversely proportional to the square of the distance between them.
52
Apply Gravity Algorithm Apply gravity from object b) to object a) { calculate the distance between the x-/y- coordinate of the objects; create a new vector using this data to determine direction; calculate the distance between the two bodies using Pythagoras´ theorem; use Newton's formula to calculate the strength of the force calculate the length (acceleration) of the vector; apply the vector to object a); }
53
Acceleration = Force / Mass
54
Appling Gravity Method Why do these numbers need to be doubles?
55
Trying it Out Try out the three initializing methods from Space object again. What do you observe?
56
Experimenting with Gravity Change the gravity constant at the top of the body class. What happens? Change it by ½, change it by doubling it; change it by 1, change it by a decimal.
57
Experimenting with Mass & Movement Experiment with changes to the mass and/or initial movement of the bodies defined in the Body class. What happens? sizemassvectormovementxyrgb When experimenting it’s important to change one variable at a time.
58
Concept Summary
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.