There’s no error, but there is a bug. code executes perfectly. here is my whole code:
Cow.pde
public class Cow {
float x, y, dx, dy, radius;
color c;
boolean colliding = false;
boolean selected = true;
float prevAngle = 0;
Cow(float rad, float x, float y, float dx, float dy) {
radius = rad;
this.x = x;
this.y = y;
this.dx = 5;//(int)(dx*100)/100.0;
this.dy = -5;//(int)(dy*100)/100.0;
c = color(random(255), random(255), random(255));
}
Cow() {
this(20+(int)(Math.random()*30), width/2, height/2, random(6)-3, random(6)-3);
}
void move() {
int mult = 1;
if (selected && colliding) {
mult = 2;
}
x += dx * mult;
y += dy * mult;
if (x + radius > width || x - radius < 0) dx *= -1;
if (y + radius > height || y - radius < 0) dy *= -1;
}
void display() {
noStroke();
if (colliding) {
fill(255, 0, 0, 100);
} else {
fill(c);
}
ellipse(x, y, radius*2, radius*2);
if (selected) {
fill(255);
ellipse(x-10, y, 5, 5);
ellipse(x+10, y, 5, 5);
}
}
void click() {
if (dist(mouseX, mouseY, this.x, this.y) <= radius) {
selected = !selected;
}
}
void collide(ArrayList<Cow> others) {
int counter = 0;
for (Cow oc : others) {
if (oc != this && dist(oc.x, oc.y, this.x, this.y) <= (oc.radius + this.radius)) {
counter ++;
}
}
if (counter > 0) colliding = true;
else colliding = false;
}
void turn(float angle) {
float newAngle = prevAngle-radians(angle);
prevAngle = newAngle;
dx = cos(newAngle)*5;
dy = sin(newAngle)*5;
}
void changeSpeed(float dv) {
this.dx += dv;
this.dy += dv;
}
}
CowDemo.pde
ArrayList<Cow> cows;
void setup() {
frameRate(30);
size(1000, 800);
//size(300, 300);
cows = new ArrayList<Cow>();
for (int i = 0; i < 1; i++) {
cows.add(new Cow());
}
}
void draw() {
background(200);
int showPos = 1;
for (Cow c : cows) {
c.collide(cows);
c.move();
c.display();
if (c.selected) {
fill(0);
text("Dx: "+c.dx+" Dy: "+c.dy, width-200, 20*showPos);
showPos++;
}
}
fill(0);
textSize(20);
text("FPS: "+frameRate+"Cows: "+cows.size(), 0, 20);
}
void mousePressed() {
if (mouseButton == RIGHT) {
cows.add(new Cow(20+(int)(Math.random()*30), mouseX, mouseY, random(6)-3, random(6)-3));
}
for (Cow c : cows) {
c.turn(90);
}
}
void keyPressed() {
if (keyCode == 32) {
cows.clear();
}
}
In this configuration, All seems working fine, except the first turn becomes wrong. I’ve set the angle to 90. but when i execute turn first time it does 45 degree angle. and then onwards it does 90 degree as intended.