GMT20221208-160759_Recording_1920x1080.mp4
Note that the following is the final code from the review session, it covers the same concepts, but it differs slightly from the following code in the examples below which was done at an earlier time:
https://editor.p5js.org/des8963/sketches/YtrHfJEN8
class Player {
constructor(aColor) {
this.x=width/2;
this.y=15;
this.d=25;
this.c=aColor;
}
draw() {
fill(this.c);
ellipse(this.x,this.y,this.d);
}
move(x,y) {
let oldx=this.x;
let oldy=this.y;
let stayInPlace=false;
this.x+=x;
this.y+=y;
if ((this.x <= 0) || (this.y <= 0) || (this.x >= width) || (this.y >= height)) {
stayInPlace=true;
}
if (stayInPlace) {
this.x=oldx;
this.y=oldy;
}
}
update() {
if (keyIsDown(LEFT_ARROW)) {
this.move(-2,0);
}
if (keyIsDown(RIGHT_ARROW)) {
this.move(2,0);
}
if (keyIsDown(DOWN_ARROW)) {
this.move(0,2);
}
if (keyIsDown(UP_ARROW)) {
this.move(0,-2);
}
}
}
// Inside Setup
function Setup() {
// ---- this is the code you add to setup for creating a Player
p=new Player(color(100,0,0));
}
function draw() {
// This is the code we add to update players position and redraw
p.update();
p.draw();
}
Create
Dealing with Collisions
Since all of our objects are going to be circles, we can tell if one circle collides into another if the distance between two circles is smaller than the sum of their radii.
i.e. Circles overlap if distance between two center points is less than r1+r2
let obstacles=[];
class Obstacle {
constructor(_x,_y) {
this.x=_x;
this.y=_y;
this.d=25;
}
draw() {
fill(100);
ellipse(this.x,this.y,this.d);
}
collide(aPlayer) {
let d=dist(aPlayer.x,aPlayer.y,this.x,this.y);
if (d<(aPlayer.d/2+this.d/2)) {
return true;
} else {
return false;
}
}
}
// Inside Player Object we need to add functions to handle collisions
class Player() {
// Note I left out constructor, draw and update from prior code example
**obstacleCollisions() {
let collided=false;
for (let i=0; i<obstacles.length; i++) {
let thisObject=obstacles[i];
if (!collided) {
collided=thisObject.collide(this);
}
}
return collided;
}**
move(x,y) {
let oldx=this.x;
let oldy=this.y;
let stayInPlace=false;
this.x+=x;
this.y+=y;
if ((this.x <= 0) || (this.y <= 0) || (this.x >= width) || (this.y >= height)) {
stayInPlace=true;
}
**if (!stayInPlace) {
stayInPlace=this.obstacleCollisions();
}**
if (stayInPlace) {
this.x=oldx;
this.y=oldy;
}
}
}
// Inside Setup
function Setup() {
// ---- this is the code you add to setup for creating obstacles
for (let i=0; i< 20; i++) {
obstacles.push(new Obstacle(random(20,width-20),random(50,height-20)));
}
}
function draw() {
// This is the code we add to display obstacles
for (let i=0; i<obstacles.length; i++) {
obstacles[i].draw();
}
}