chapter 6 – interacting objects: newton’s lab. topics: objects interacting with each other,...

Post on 02-Jan-2016

236 Views

Category:

Documents

4 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Chapter 6 – Interacting Objects:

Newton’s Lab

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.

Newton’s lab

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

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.

The Space class: - 3 configurations of Space

What happens when you activate one of these methods?

Right-click on the Space world background

Space Public Methods

Constructors within Constructors ?

Inspecting Body Methods

Right – click on a body. What methods does it have?

Inspecting Body Properties

Right click on a planet and inspect its properties. How does the object store its position?

Inspecting Body Properties

Each Body holds a Vector object.What does the Vector object represent?

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.

Helper Classes for Import Edit Menu / Import Class…

Some Helper Classes•Animal•Counter•GifImage•Label•Map•Plotter•ScoreBoard•SimpleTimer•SmoothMover•Weather

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

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.

Methods Inherited from SmoothMover

SmoothMover objects have the same method (setLocation) twice. How do they differ? Why are they necessary?

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.

Vector Class Variables

The Vector class implements BOTH Polar and Cartesian representation.All necessary conversions are handled within the class.

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?

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

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?

Default and non-DefaultConstructors

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.

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.

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.

Change act() so that it moves without applying any forces

Body Behavior

Create multiple bodies. How do they behave?

Add Movement (Left)

How would you make the body move left?

How to make objects go left?

0360

-27090

-90270

-180180

/** * 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

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;

Importing Java Color Library

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

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

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

Other Predefined Colors:

The Color class

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

Default Color of Body

Calls the Color class.

Sets the RBG values

What is the legal range for colors?

Adding Gravitational

Force

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

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;

{

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.

Greenfoot World Methodshttp://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.

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.

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?

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?

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<String>

List<Actor>

Apply Force – Part II

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”.

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.

Applying Gravity

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;

{

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.

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);

}

Acceleration

Acceleration =

Force / Mass

Appling Gravity Method

Why do these numbers need to be doubles?

Trying it Out

Try out the three initializing methods from Space object again. What do you observe?

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.

Experimenting with Mass & Movement

Experiment with changes to the mass and/or initial movement of the bodies defined in the Body class. What happens?

size mass vector movement x yr g b

When experimenting it’s important to change one variable at a time.

Concept Summary

top related