Object that chases another object
in
Programming Questions
•
1 month ago
I was just messing around / experimenting with classes and I wanted to make a cat object with a class, and a dog object which will basically chase the cat around.
I have a seek() method for the dog (like in Nature of Code chapter 6)
but I can't figure out how to make the force that moves the dog
but I can't figure out how to make the force that moves the dog
Does anyone Know how to make a basic "force", (kinda like in Nature of Code chapter 2)?
there's probably no reason to put all the code but here it is, sorry for the sloppyness
- class Dog {
PVector location;
PVector velocity;
PVector acceleration;
float maxspeed;
float maxforce;
float r; // the size
Dog(float x, float y) {
acceleration = new PVector(0,0);
velocity = new PVector(0,0);
location = new PVector(x,y);
r = 8.0;
maxspeed = 4;
maxforce = 0.1;
}
void update() {
velocity.add(acceleration);
velocity.limit(maxspeed);
acceleration.mult(0);
}
void applyForce(PVector force) {
acceleration.add(force);
// force.div(mass);
//force.sub(energy);
}
void seek(PVector target) {
PVector desired = PVector.sub(target,location);
desired.normalize();
desired.mult(maxspeed);
PVector steer = PVector.sub(desired,velocity);
steer.limit(maxforce);
applyForce(steer);
}
-
void display() {
- }
//end
}
Main
- Cat myCat1;
Cat myCat2;
Dog myDog;
PVector goal;
void setup() {
size(300,300);
//Cat( tempC, tempXpos, tempYpos, tempXspeed, tempXdir, tempYdir) {
myCat1 = new Cat(color(112,250,86), 50, 10, 1, 1, 1);
myCat2 = new Cat(color(173,86,250), 50, 100, 2, -1, 1);
myDog = new Dog(50,50);
//goal = new PVector(Cat.xpos, Cat.ypos);
}
void draw() {
background(0);
myCat1.live();
myCat1.display();
myCat2.live();
myCat2.display();
goal = new PVector(myCat1.xpos, myCat1.ypos); // IS THAT THE RIGHT WAY TO USE VARIABLES FROM THE OTHER CLASS?
myDog.applyForce();
myDog.seek(goal);
myDog.display();
println(myCat1.xpos);
}
Cat class
- class Cat {
color c;
float xpos;
float ypos;
float xspeed;
float xdir;
float ydir;
int rad = 10;
//
// the constructer is defined with arguments
//
Cat(color tempC, float tempXpos, float tempYpos, float tempXspeed, float tempXdir, float tempYdir) {
c = tempC;
xpos = tempXpos;
ypos = tempYpos;
xspeed = tempXspeed;
ydir = tempYdir;
xdir = tempXdir;
//targeter = new PVector(xpos,ypos);
}
void display() {
stroke(0);
fill(c);
rectMode(CENTER);
rect(xpos,ypos,rad,rad);
}
void live() {
xpos = xpos + (xspeed * xdir);
ypos = ypos + (xspeed * ydir);
if (xpos > width - rad || xpos < rad) {
xdir *= -1;
}
if (ypos > height - rad || ypos < rad) {
ydir *= -1;
}
}
}
1