Skip to content

Instantly share code, notes, and snippets.

@otarza
Created July 18, 2019 04:40
Show Gist options
  • Save otarza/b4c328594faa087ccd944eec3900cc63 to your computer and use it in GitHub Desktop.
Save otarza/b4c328594faa087ccd944eec3900cc63 to your computer and use it in GitHub Desktop.
Avoid the mines by szabo
let bob;
let bobDiameter = 30;
let mines = [];
let mineDiameter = 20;
let m;
let avoideThisMine;
let Mine = function(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
this.show = function(){}
}
function setup() {
createCanvas(600, 400);
bob = new Soldier();
//craeres i num of mines
for (let i = 0; i < 10; i++) {
let x = random(0 + mineDiameter / 2, width - mineDiameter / 2);
let y = random(0 + mineDiameter / 2, height - mineDiameter / 2);
let r = mineDiameter;
m = new Mine(x, y, r);
mines.push(m);
//print(mines[i]);
}
// print(mines[1]);
// print(mines[i].x, mines[i].y);
}
function draw() {
background(220);
for (let i = 0; i < mines.length; i++){
let d = dist(mines[i].x, mines[i].y, bob.pos.y, bob.pos.y)
if(d < bobDiameter + mineDiameter){
avoideThisMine = createVector(mines[i].x, mines[i].y);
print(bob.pos());
}
}
for (mine of mines) {
mine.show();
}
bob.avoidWalls();
bob.walk();
bob.display();
}
class Soldier {
constructor() {
this.pos = createVector(width / 2, height / 2);
this.vel = createVector(0, 0);
this.maxSpeed = 0.2;
this.r = bobDiameter;
}
//with this function soldier avoides canvas walls
avoidWalls() {
if (this.pos.x < 0 + 15) { //for left wall
this.pos.x = 16;
this.vel.x = this.vel.x * -0.9;
}
if (this.pos.x > width - 15) { //for right wall
this.vel.x = this.vel.x * -0.9;
this.pos.x = width - 16;
}
if (this.pos.y < 0 + 15) { //for top wall
this.vel.y = this.vel.y * -0.9;
this.pos.y = 16;
}
if (this.pos.y > height - 15) { //for bottom wall
this.vel.y = this.vel.y * -0.9;
this.pos.y = height - 15;
}
}
//physics engine - soldier walkes randomly on canvas with vel. and acc.
walk() {
this.vel.limit = this.maxSpeed;
this.acc = createVector(random(-1, 1), random(-1, 1));
this.acc.setMag(0.1);
//this.acc.normalize();
this.vel.add(this.acc);
this.pos.add(this.vel);
}
//soldier is shown on canvas
display() {
fill(0, 200, 0);
stroke(0);
strokeWeight(1);
ellipse(this.pos.x, this.pos.y, this.r/2, this.r*1.7); //shoulders
ellipse(this.pos.x, this.pos.y, this.r, this.r); //hat
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment