Created
January 4, 2015 11:50
-
-
Save darkwave/a432d4f1cd7464559f4a to your computer and use it in GitHub Desktop.
Move along path Agent.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Agent player; | |
void setup() { | |
size(640, 480); | |
player = new Agent(new PVector(width / 2, height / 2)); | |
ArrayList<PVector> newPath = new ArrayList<PVector>(); | |
newPath.add(new PVector(100, 100)); | |
newPath.add(new PVector(80, 200)); | |
newPath.add(new PVector(150, 300)); | |
player.newPath = newPath; | |
} | |
boolean updatePath = false; | |
ArrayList<PVector> updatedPath; | |
void draw() { | |
//player.currentTarget = new PVector(mouseX, mouseY); | |
if (updatePath) { | |
player.setPath(updatedPath); | |
updatePath = false; | |
} | |
background(66); | |
for (PVector node: player.path) { | |
ellipse(node.x, node.y, 6, 6); | |
} | |
player.update(); | |
player.display(); | |
} | |
void mouseReleased() { | |
updatePath = true; | |
} | |
void mousePressed() { | |
updatedPath = new ArrayList<PVector>(); | |
updatedPath.add(new PVector(mouseX, mouseY)); | |
} | |
void mouseDragged() { | |
//TODO add min distance between path nodes | |
PVector lastNode = updatedPath.get(updatedPath.size() - 1); | |
if (dist(mouseX, mouseY, lastNode.x, lastNode.y) > 10) | |
updatedPath.add(new PVector(mouseX, mouseY)); | |
} | |
class Agent { | |
PVector pos, currentTarget; | |
ArrayList<PVector> path = new ArrayList<PVector>(); | |
ArrayList<PVector> newPath; | |
int pathIndex = 0; | |
Agent(PVector _pos) { | |
pos = _pos; | |
currentTarget = pos; | |
newPath = path; | |
} | |
void setPath(ArrayList<PVector> _newPath) { | |
newPath = _newPath; | |
} | |
void update() { | |
if (newPath != path) { | |
path = newPath; | |
pathIndex = -1; | |
currentTarget = path.get(0); | |
} | |
float distance = PVector.dist(pos, currentTarget); | |
if (distance < 3) { | |
if (path.size() > 0) { //check for path | |
pathIndex++; | |
if (pathIndex == path.size()) { //arrived | |
path.clear(); | |
pathIndex = -1; | |
return; | |
} | |
currentTarget = path.get(pathIndex).copy(); | |
} | |
return; | |
} | |
float deltaX = currentTarget.x - pos.x; | |
float deltaY = currentTarget.y - pos.y; | |
float angle = atan2(deltaX, deltaY); | |
pos.x += sin(angle) * 3; | |
pos.y += cos(angle) * 3; | |
} | |
void display() { | |
pushMatrix(); | |
translate(pos.x, pos.y); | |
ellipse(0, 0, 20, 20); | |
popMatrix(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment