/** * This program animates a ball bouncing in a rectangular box. */ import processing.core.PApplet import ddf.minim.* fun main(args: Array) { PApplet.main("BallSketch") } class BallSketch : PApplet() { val resources = "src/resources" val ballImage by lazy { loadImage("$resources/earth.gif") } lateinit var laserPlayer: AudioPlayer lateinit var popPlayer: AudioPlayer val ballRadius = 10F // The following two numbers are gotten by trial and error. val minV = 1.0F // minimum velocity val maxV = 6.8F // maximum velocity var px = 0F // x-coordinate of position var py = 0F // y-coordinate of position var vx = 0F // x-coordinate of velocity var vy = 0F // y-coordinate of velocity var minX = 0F var maxX = 0F var minY = 0F var maxY = 0F override fun settings() { size(640, 480) minX = ballRadius maxX = width - ballRadius minY = ballRadius maxY = height - ballRadius } override fun setup() { val minim = Minim(this) laserPlayer = minim.loadFile("$resources/laser.wav") popPlayer = minim.loadFile("$resources/pop.wav") // picks a random starting position for the ball px = random(minX, maxX) py = random(minY, maxY) // picks a random starting velocity for the ball vx = random(minV, maxV) vy = random(minV, maxV) } override fun draw() { // finds the new position of the ball if ((px + ballRadius) !in minX..maxX) { vx = -vx laserPlayer.rewind() laserPlayer.play() } if ((py + ballRadius) !in minY..maxY) { vy = -vy popPlayer.rewind() popPlayer.play() } px += vx py += vy // draws the background, and then the ball background(200) image(ballImage, px, py) } }