text, and mouse

advertisement
More with Processing:
Text and Animation
Console Printing
 Prints to the small output window on the Processing
application
 print(“Hey!”);
 print(x);
 To go to the next line:
 println(“Hey – go down a line!”);
Fonts





Probably, you want to type to the applet window.
We need to create a .vlw font
Go to Tools -> Create Font
Find the one you like
In your sketch folder you will see a folder named data,
and in it is your font file.
Text writing commands
Whatever your font is
named
Pfont font;
font = loadFont("ACaslonPro-BoldItalic-48.vlw");
textFont(font);
My message will be red!
fill(255,0,0);
text(“Hello!”, 100, 100);
Draw it at (100,100)
Text size
 A font used at the same size it’s created looks best.
But you can change the size of your text:
 textSize(12);
 If we need to know how wide our message is, we can
type
 float width = textWidth(“My message”);
Follow the Mouse
 use mouseX and mouseY to draw instead and watch
the text follow the mouse!
 text("Hello!", mouseX, mouseY);
Animation
 We can animate our message by changing the x,y
values of where we write the text.
 Keep the current values of x,y outside the methods so
that I can access them at any point.
// Make all the variables I need
float x = 100;
float y = 100;
PFont font;
// This happens once
void setup(){
size(400,400);
font = loadFont("ACaslonPro-BoldItalic-48.vlw");
textFont(font);
}
// This happens over and over
void draw(){
background(255,255,255);
fill(255,0,0);
x=x+1;
y=y+1;
text("Hello!",x,y);
}
Background drawing
 What happens if I move the background line to the
setup method? Try it!
Keep it in bounds
Use an if statement:
if(x > 400){
x = 0;
}
Means: if the x variable is bigger than the width of the
screen, reset it to 0. Do this for y also.
Your turn
 Can you change the code so that it wraps around
when the right-most edge of the text is off screen
rather than the left-most edge?
 Hint: Use textWidth!
Bounce
 Let’s make the word bounce around rather than
wrap. To do this we will use the idea of a velocity –
how many pixels the word moves in each direction.
 Add variables near x and y for dx and dy.
 Change the code that moves the words to
 x = x + dx;
 y = y + dy;
Bounce
 What should happen to the velocity when a boundary
is hit? Can you write the if statements?
More if statements
 And : &&
if (x<0 && y < 0){
 Or: ||
if ( x < 0 || y < mouseY){
 What do you think it does?
if (y>400 || mousePressed){
dy = dy * -1;
}
And more…
if(x<300){
x = x + dx;
}
else{
x =x – dx;
}
Can you…
 Make the word move faster with each bounce?
 Write on the screen how many times the bounce
happens?
 Make the text change color when it bounces?
 Make it follow the mouse when the button is pressed,
but bounce otherwise?
Download