Constraining object movement to an ellipse.
in
Programming Questions
•
1 year ago
Following the fabulous
Nature of Code tutorials by Dan Shiffman, I've replicated following simple sketch:
A single object is repulsed by the mouse pointer. Currently the object can move freely around the stage, but what I'm trying to achieve, is to have the object move away from the cursor, but at the same time be fixed to a "rail" (the red ring in the sketch).
But I have no clue how to achieve this. I'm thinking it may become quite complex, because I apply the repulsion force to the object, but since it only can move on a curved path, said force may act upon the object in ways I can't yet see. (Or lack the essential math for).
Any pointers to how I could tackle this problem would be greatly appreciated.
- Thing t;
- void setup() {
- size(250, 250);
- background(0);
- t = new Thing();
- }
- void draw() {
- background(0);
- // the ball should move on this rail.
- noFill();
- stroke(255, 0, 0);
- ellipse(width/2, height/2, width*.75, height*.75);
- // render object
- t.render();
- }
- // class
- class Thing {
- PVector loc, vel, acc;
- float topspeed;
- Thing() {
- loc = new PVector(random(width), random(height));
- vel = new PVector(0, 0);
- topspeed = 4;
- }
- void update() {
- PVector mouse = new PVector(mouseX, mouseY);
- PVector dir = PVector.sub(mouse, loc);
- dir.normalize();
- dir.mult(-0.1);
- acc = dir;
- vel.add(acc);
- vel.limit(topspeed);
- loc.add(vel);
- }
- void render() {
- update();
- warpEdge();
- display();
- }
- void display() {
- noStroke();
- fill(255);
- ellipse(loc.x, loc.y, 20, 20);
- }
- // if object reaches edge, "warp" to opposite side
- void warpEdge() {
- if (loc.x > width) {
- loc.x = 0;
- }
- else if (loc.x < 0) {
- loc.x = width;
- }
- if (loc.y > height) {
- loc.y = 0;
- }
- else if (loc.y < 0) {
- loc.y = height;
- }
- }
- }
Slightly off-topic addendum: Dan has
kickstarted his NoC tutorials into a book! Currently he has outlined all chapters and is finalizing the layout and design. I am a project backer and have read some draft chapters. This thing will be awesome! So, if you are into this kind of programming, I highly recommend you keep an eye out for the final release.
1