nature-of-code/1. Vectors/3. Bouncing ball/sketch.js

63 lines
1.4 KiB
JavaScript

let position
let velocity
let topLeftCorner
let bottomRightCorner
function setup() {
createCanvas(300, 300, WEBGL)
topLeftCorner = createVector(-100, -100, -100)
bottomRightCorner = createVector(100, 100, 100)
position = createVector(0, 0)
velocity = createVector(
random(3) - 1,
random(3) - 1,
random(3) - 1,
).mult(0.2)
}
function draw() {
position.add(p5.Vector.mult(velocity, deltaTime))
if (position.x < topLeftCorner.x || position.x > bottomRightCorner.x) {
velocity.x *= -1
}
if (position.y < topLeftCorner.y || position.y > bottomRightCorner.y) {
velocity.y *= -1
}
if (position.z < topLeftCorner.z || position.z > bottomRightCorner.z) {
velocity.z *= -1
}
background(255)
noFill()
orbitControl()
stroke('red')
point(topLeftCorner)
stroke('blue')
point(bottomRightCorner)
stroke('black')
strokeWeight(0.5)
push()
translate(p5.Vector.add(topLeftCorner, bottomRightCorner).div(2))
let boundsWidth = abs(topLeftCorner.x - bottomRightCorner.x)
let boundsHeight = abs(topLeftCorner.y - bottomRightCorner.y)
let boundsDepth = abs(topLeftCorner.z - bottomRightCorner.z)
box(boundsWidth, boundsHeight, boundsDepth)
pop()
strokeWeight(2)
orbitControl()
push()
translate(position)
sphere(5)
pop()
}