PApplet
class.PApplet
is a rectangular screen consisting of addressable pixels, each of which is located by a pair of numbers (\(x\), \(y\)).sketch
by drawing shapes, displaying images, and performing other manipulations to create an artwork.runSketch()
or main()
.runSketch()
by default works by first executing settings()
once, then executing setup()
once, then loops forever executing the draw()
function at the rate specified by frameRate
.noLoop()
within setup()
to disable looping. Or she can call frameRate()
to change the default (60 fps) frameRate
to some other value.Here is a template of a Kotlin program that calls the main()
function of the PApplet
class to run the sketch MySketch
:
import processing.core.PApplet
fun main(args: Array<String>) {
PApplet.main("MySketch");
}
class MySketch : PApplet() {
override fun settings() {
size(200, 200) // change the numbers to suit your application
}
override fun setup() {
// write your setup code here
}
override fun draw() {
// write your draw code here
}
}
settings()
you can call functions that set up the screen parameters only. Such functions are size()
, fullScreen()
, smooth()
, etc.setup()
you can call functions that create images, load images, draw images, configure the colors, thickness, and style of various things like screen background, fill colors, strokes, etc. You can also control whether or not you want to do animation by calling loop()
or noLoop()
.draw()
you can call the same functions as in setup()
.There are a number of PApplet functions for detecting occurrences of various keyboard and mouse events while running an animation. However, these event-driven functions work only when you also provide a draw()
function, even if it were an empty one. Event-driven functions include keyPressed()
, keyReleased()
, keyTyped()
, mouseClicked()
, mouseDragged()
, mouseMoved()
, mousePressed()
, mouseReleased()
, and mouseWheel()
. To customize your sketch so that it responds appropriately to the events it’s listening for, you override their respective functions. For example, to customize keyPressed()
you would write
override fun draw() {
// your code here (might even be empty)
}
override fun keyPressed() {
// your code here
}
This kotlin program draws 50 random figures on the screen. Each figure is either a rectangle or a circle, but its dimension, color, and position are randomly determined.
import processing.core.PApplet
const val HOW_MANY_FIGURES = 50
fun main() {
PApplet.main("RandomRectsCirclesSketch")
}
class RandomRectsCirclesSketch : PApplet() {
override fun settings() {
size(400, 400)
}
override fun setup() {
rectMode(CENTER)
noLoop()
}
override fun draw() {
repeat(HOW_MANY_FIGURES) {
val x = random(1F, width.toFloat())
val y = random(1F, height.toFloat())
fill(random(256F), random(256F), random(256F))
if (random(2F) < 1F) {
val size = random(10F, 60F)
ellipse(x, y, size, size)
} else {
val w = random(10F, 60F)
val h = random(10F, 60F)
rect(x, y, w, h)
}
}
}
}