Creative Computing. Comments on Assignments Everyone did very well Report writing needs more work Jumping scale Update first then draw.

Post on 28-Mar-2015

217 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

Transcript

Creative Computing

Creative Computing Comments on AssignmentsEveryone did very wellReport writing needs more workJumping scaleUpdate first then draw

Creative Computing

\\ aims

By the end of the session you will be able to:

1. Use Loops and Arrays to control the behaviour of multiple objects

2. Create a class3. Embed data and code in a class4. Create basic behaviours of

multiple objects moving and interaction with each other

Creative Computing \\ Objects and BehaviourLots of our programs involve “things” that move around and interact

Often we want lots of these things

How do we handle many interacting objects?

Creative Computing

\\ Loops and arrays

The answer is with loops and arrays

Gone over last week as well as in java

Creative Computing \\ Instructions and dataA program consists of 2 thingsInstructionsThe commands we givee.g. size(200,200); x = x+y;

DataThe variables, “state” of a programe.g. int x = 100;

Creative Computing \\ Instructions and dataInstructions are typed into a program in a sequence from top to bottom

They are executed one by oneBut the real power comes when you change the order

Creative Computing \\ Instructions and dataInstructions are typed into a program in a sequence from top to bottom

They are executed one by oneBut the real power comes when you change the orderIf statements select particular commands to execute

Creative Computing \\ Instructions and dataInstructions are typed into a program in a sequence from top to bottom

They are executed one by oneBut the real power comes when you change the orderLoops execute commands multiple times

Creative Computing

\\ Loops

Loops let you do a set of commands many times while only typing them once

More importantly, you don’t need to know how many times until you get to the loop

Creative Computing

\\ Arrays

You also want to do the same thing with data

Have many repeated data itemGive them a single nameArrays

Creative Computing

\\ Arrays

0 1 2 3 4

X[2]

Creative Computing

\\ Arrays and Loops

Arrays and Loops go very well together

There isn’t much use to having arrays unless you can step through them and do stuff to each element

Loops do just that

Creative Computing

\\ Arrays and Loopsint X[] = new int[30];

for (int i = 0; i < X.length; i++){

X[i] = i*3;}

Creative Computing \\ Objects and BehaviourLots of our programs involve “things” that move around and interact

Often we want lots of these things

How do we handle many interacting objects?

Creative Computing \\ Objects and BehaviourYou can use Arrays to store data about our objectse.g. position, velocity

Loops to create their behaviour

Creative Computing

// the number of ballsint ballNumber = 20;

// The data we need to know about balls// This is the "State" of the program// As we have multiple balls we need to hold their state // we use a set of array with a posiion for each ball

// the size of a ballint ballSize = 10;

// the x and y positionfloat xPos[], yPos[];

// the velocityfloat xVel[], yVel[];

Creative Computingvoid setup(){ size(500, 500); // create all the arrays xPos = new float[ballNumber]; yPos = new float[ballNumber]; xVel = new float[ballNumber]; yVel = new float[ballNumber]; // put data in them // create a random position and velocity for each for (int i = 0; i < ballNumber; i++) { // create a random position on the screen // make sure all positions are at least // ballSize from the edge of the screen

xPos[i] = random(ballSize, width -ballSize); yPos[i] = random(ballSize, height-ballSize); // random small velocities between -2 and 2 xVel[i] = random(-2, 2); yVel[i] = random(-2, 2); }}

Creative Computing

void draw(){ background(255); // update all the balls for (int i = 0; i < ballNumber; i++) { // update the position of the ball // by adding on the velocity xPos[i] += xVel[i]; yPos[i] += yVel[i]; // draw the ball strokeWeight(4); ellipse(xPos[i], yPos[i], ballSize, ballSize); }}

Creative Computing \\ Objects and BehaviourDoesn’t seem quite rightxPos, xVel etc. are all features of a ball

Don’t they some how belong together, not in separate arrays?

Shouldn’t we somewhere have something that represents a ball?

That is where classes come in.

Creative Computing

\\ Classes

Classes are a way of putting data that belong together in the same place

They can represent real world things like balls

You use them to create your own types

Creative Computing

\\ Classes

Rather than having an array of positions and an array of velocities

You can have an array of ballsA ball contains a position and a velocity

Creative Computing

\\ Classes

A class is like a new type (int, float etc.)

It represents a generic class like “Balls”

A particular ball is an “object”, e.g. a variable of type Ball

Creative Computing

// create a class to represent a ball class Ball{ // all the data for the ball is now // stored in the class float xPos, yPos; float xVel, yVel; float Size;}

Ball ball = new Ball();ball.xPos = 100;

Creative Computing

\\ new and dot

To create an object of a class you use the keyword new

You can put the result in a variable

To access a variable (member) of a class, you use a dot “.”

Creative Computing

// create a class to represent a ball class Ball{ // all the data for the ball is now // stored in the class float xPos, yPos; float xVel, yVel; float Size;}

Ball ball = new Ball();ball.xPos = 100;

Creative Computing

\\ Classes

We can now create an array of Ball objects

Use them in our simulation instead of individual arrays

Much tidier

Creative Computing

// Now we only need one array to hold all the ballsBall balls[];

void setup(){ size(500, 500); // create an array of balls balls = new Ball[ballNumber]; // Add new items to the array for (int i = 0; i < balls.length; i++) { balls[i] = new Ball(); // set up the data for the ball balls[i].Size = 10; // create a random position on the screen // make sure all positions are at least // ballSize from the edge of the screen balls[i].xPos = random(balls[i].Size, width -balls[i].Size); balls[i].yPos = random(balls[i].Size, height-balls[i].Size); // random small velocities between -2 and 2 balls[i].xVel = random(-2, 2); balls[i].yVel = random(-2, 2); }}

Creative Computing

void draw(){ background(255); // update an draw the balls for (int i = 0; i < balls.length; i++) { balls[i].xPos += balls[i].xVel; balls[i].yPos += balls[i].yVel; // draw the ball strokeWeight(4); ellipse(balls[i].xPos, balls[i].yPos, balls[i].Size, balls[i].Size); } }

Creative Computing

Create a class for a ball Using that class create a program where multiple balls move around bouncing off the edges of the screen

Extra: can you create more complex behaviour?

Extra: can you make the balls interact with each other?

\\ Exercises

Creative Computing

I’m still not that happyWe’ve now put all the data for a ball together

But there are also instructions that relate to ballse.g. moving and drawing

Shouldn’t they go in the class as well?

Yes: Methods

\\ Classes

Creative Computing

Instructions are grouped together into blocks

Curly brackets create blocks {}

E.g. Loops, if statements, functions

\\ Blocks of code

Creative Computing

if (i < 100){

// this is one block}else{

// this is another}

for (int i = 0; i < 100; i++){

// this is a third block}

Creative Computing

You can think of these as block of code that you can call in other places

A way of being able to reuse blocks of code

A bit like a variable allows us to reuse data

\\ Functions

Creative Computing

int ballx = 10;int bally = 10;

// a functionvoid drawBall(){

ellipse(ballx, bally, 10, 10);}

// another functionvoid setup(){

for (int i = 0; i < 100; i++){

ballx += 10;drawBall();

}}

Creative Computing

A method is a function that is attached to a class

It allows us to put both data and instructions together in a single class

The behaviour of the class becomes part of the class

\\ Methods

Creative Computingclass Ball{

float xPos, yPos, xVel, yVel; float Size;

// a constructorBall()

{ } // Update the position of the ball void update() { } // draw the ball on screen void draw() { } }

Creative Computing

You can add whatever methods you like to a class

You call methods using the dot “.” notation just like member variables

\\ Methods

Creative Computing

Classes have special methods called “constructors”

They are called when the class is created

A bit like a “setup” method for a class

They have the same name as the class

\\ Constructors

Creative Computing

Constructors are used to set up all the data in the class

Provide initial values to all the variables

\\ Constructors

Creative Computingclass Ball{ float xPos, yPos, xVel, yVel; float Size;

// a constructorBall()

{ // set the value of the size Size = 10.0; // set up the initial positions to random values xPos = random(Size, width-Size); yPos = random(Size, height-Size); // set up random velocities xVel = random(-2, 2); yVel = random(-2, 2); } }

Creative Computing

All you need to do now is create an object of the class

The variables now set themselves up in the constructor

\\ Constructors

Creative Computing

// Now we only need one array to hold all the ballsBall balls[];

void setup(){ size(500, 500); // create an array of balls balls = new Ball[ballNumber]; // Add new items to the array for (int i = 0; i < balls.length; i++) { balls[i] = new Ball(); }}

Creative Computing

A good way of simulating behaviour is to have a set of 3 methods

ConstructorUpdateDraw

\\ Simulating behaviour

Creative Computing

A good way of simulating behaviour is to have a set of 3 methods

ConstructorSets up all the variables

UpdateDraw

\\ Simulating behaviour

Creative Computing

A good way of simulating behaviour is to have a set of 3 methods

ConstructorUpdate

Updates the variables each frame

e.g. changes the positionDraw

\\ Simulating behaviour

Creative Computing

A good way of simulating behaviour is to have a set of 3 methods

ConstructorUpdateDrawDraw the object to the screen

\\ Simulating behaviour

Creative Computingclass Ball{

float xPos, yPos, xVel, yVel; float Size;

// a constructorBall()

{ } // Update the position of the ball void update() { xPos += xVel; yPos += yVel; } // draw the ball on screen void draw() {

strokeWeight(4); ellipse(xPos, yPos, Size, Size); }}

Creative Computing

Update and draw can then be called from the main draw function

\\ Simulating behaviour

Creative Computing

void draw(){ background(255);

// update and draw the balls for (int i = 0; i < balls.length; i++) { balls[i].update(); balls[i].draw(); }}

Creative Computing

Take your existing code and rewrite it using methods

\\ Exercises

Creative Computing

\\ aims

By the end of the session you will be able to:

1. Use Loops and Arrays to control the behaviour of multiple objects

2. Create a class3. Embed data and code in a class4. Create basic behaviours of

multiple objects moving and interaction with each other

Creative Computing

\\ Behaviours

Now we’d like our objects to do some more interesting things

I’m going to go through a bunch of behaviours

SeekFleeObstacle avoidance

Creative Computing

\\ Seek

Head towards an objectEach frame we update the

velocity so that we are getting closer to a target

Add a small factor in the direction of the target

Creative Computing

\\ Seek

How do we work out the direction between two objects?

Subtract their positionsxDir = target.ball.xPosyDir = target.ball.yPos

Creative Computing

\\ Seek

Subtract the balls position from the targets positionball.vel = ball.vel + (target.pos - ball.pos)

This would take us there in one stepBut don’t want it to move so fast,

so only use a fractionball.vel = ball.vel + (target.pos - ball.pos)/c

Where c is a constant

Creative Computing

\\ Flee

The opposite of seekRun away from the target

ball.vel = ball.vel - (target.pos - ball.pos)/c

Creative Computing

\\ Obstacle Avoidance

Want to be able to move around without bumping into obstacles

Could just flee from all obstacles, but you don’t want to avoid ones that are very far away

Make the change inversely proportional to the distance squared

Creative Computing

\\ Obstacle Avoidance

How do we work out the distancePythagoras’ Theorem

x

yh

h2 = x2 + y2

Creative Computing

\\ Obstacle Avoidance

h2 = x2 + y2

Distanceh = sqrt(x2 + y2)

Directionx/h, y/h

Creative Computing

\\ Obstacle Avoidance

dirx = obstacle.posx – ball.posxh = sqrt(dirx*dirx + diry*diry)dirx = dirx/hdirx = disp/hball.velx = ball.velx –

(dirx)/(h*h)

Creative Computing

\\ Obstacle Avoidance

Lots of other ways of doing it

Creative Computing

Implement Seek behaviour (to the mouse?)

Create an obstacle classGet your objects to avoid the obstacles

\\ Exercises

Creative Computing

\\ aims

By the end of the session you will be able to:

1. Use Loops and Arrays to control the behaviour of multiple objects

2. Create a class3. Embed data and code in a class4. Create basic behaviours of

multiple objects moving and interaction with each other

Creative ComputingCraig Reynolds - flockingThe first behavioural simulation

Simulates the behaviour of flocks of birds (biods), schools of fish or herds of animals

Extensively used in films and other applications

“Flocks, herds and schools: a distributed behavioural model” Craig Reynolds SIGGRAPH 1987

Creative Computing

Boids

Craig Reynold’s work was an early aspect of the artificial life field

He observed the behaviour of real flocks of birds and tried to figure out rules of their behaviour

The resulting rules are surprisingly simple

Creative Computing

Boids

SeparationAlignmentCohesion

Creative Computing

Boids

SeparationSteer away from flockmates that are very close

Creative Computing

Boids

Alignment:Match direction to the average direction of nearby flockmates

Creative Computing

Boids

Cohesion:Move towards the centre of mass of nearby flockmates

Creative ComputingBoids: Action SelectionNeed some way of combining the behaviours

They have a prioritySeparationAlignmentCohesion

But it isn’t absolute

Creative ComputingCraig Reynolds - flockingEmergent Behaviour

These simple rules produce surprising results

Here is a flock splitting to avoid an obstacle

They recombine afterwards, just like a real flock

Creative Computing

\\ Assignment

In this assignment you will be creating a flocking simulation

1. (20 %)Create a program in which a number of object move around the screen with different velocities and bounce of the edges of the window. Use a class to represent the objects.

Creative Computing

\\ Assignment

2. (40 %)Make your objects flock using Reynolds’s 3 rules of flocking

SeparationAlignmentCohesion

Creative Computing

\\ Assignment

3. (10 %)As well as flocking make the objects move towards the mouse pointer so that you can control the movement of the flock using the mouse.

4. (10 %)10 further marks will be added for creative extensions to the program.

Creative Computing

\\ Assignment

5. (20 %)Submit:A written report on your implementation,

explaining what method you used for each stage.

2 images of your program running for each stage, before and after moving the mouse.

The code files, with comments, explaining each part of the code.

Creative Computing

\\ More classes

We can still do more in terms of classes

xPos and yPos are both really two parts of a position

What we call it is a vector

Creative Computing

\\ Vectors

A vector is a pair of (x, y)v = (x,y)

It is a powerful mathematical tool for representing points in space

Treat as a single thinge.g.

v1 + v2 = (v1.x + v2.x, v1.y + v2.y)v1 - v2 = (v1.x - v2.x, v1.y - v2.y)

Creative Computing

\\ Vectors

v1

v1.x

v1.y

Creative Computing

\\ Vectors

A lot of useful operations on vectors

The magnitude of a vector is its length

Pythagoras’ theorem:v.mag() = sqrt(v.x*v.x + v.y*v.y)

Creative Computing

\\ Vectors

The direction of a vector is the same vector but with length 1

Divide the vector by its magnitude

Called normalisingv.normalize = v/v.mag()

Creative Computing

\\ Vectors

You subtract one vector from another to get the displacement of one vector from anotherdisp = v1-v2

Creative Computing

\\ Vectors

v1

v2

v1 – v2

Creative Computing

\\ Vectors

We can therefore work out the distance between two points by taking magnitude of their displacementdisp = v1 – v2distance = disp.mag()

Creative Computing

\\ Vectors

Processing has its own built in class for vectors

PVector (version 158 and later)

Creative Computing

\\ Behaviours

We can use vectors to create some more complex behaviours

top related