Following a mouse around a circle

edited April 2017 in Questions about Code

Hello, I wanted to have a triangle move around a circle to follow the mouse but it had to have a delay so it takes time for the triangle to reach the mouse I got that working but when you move the mouse over to te left top side while the triangle is left down side the triangle moves around the circle trough the right side which takes way longer, although I do understand why this happens I have no Idea how to solve this

Could anyone help me out? also, I've attached the code below

int x, y;
float current_ship;
float target_ship;

void setup() { 
  fullScreen(); 
  ellipseMode(CENTER); 
} 


void draw() { 
  background(255); 
  ellipse(width/2, height/2, 200, 200); 

  target_ship = atan2(mouseY - height/2, mouseX - width/2);

  if(target_ship > current_ship) current_ship += 0.05;
  if(target_ship < current_ship) current_ship -= 0.05;

  x = int(width/2+165*cos(current_ship)); 
  y = int(height/2+165*sin(current_ship)); 

  pushMatrix(); 
  translate(x, y); 
  rotate(atan2( mouseY - height/2, mouseX - width/2)-PI/2); 
  triangle(-30, -10, 0, +50, +30, -10); 
  popMatrix(); 
} 

Answers

  • You understand the problem? Okay. Then the solution is that you need more than one target, and it needs to move towards the closest target. What is a target value representing? Are there any other values that represent the "same" "target"? How much would they be "offset" by?

  • Answer ✓

    And a possible full-code solution too! (Don't read if you're interested in solving it yourself!)

    int x, y;
    float current_ship;
    float target_ship;
    
    void setup() { 
      fullScreen(); 
      ellipseMode(CENTER); 
    } 
    
    
    void draw() { 
      background(255); 
      ellipse(width/2, height/2, 200, 200); 
    
      target_ship = atan2(mouseY - height/2, mouseX - width/2);
    
      float target_0 = target_ship;
      float target_1 = target_ship+TWO_PI;
      float target_2 = target_ship-TWO_PI;
      float d0 = abs(current_ship - target_0);
      float d1 = abs(current_ship - target_1);
      float d2 = abs(current_ship - target_2);
      float min = min(d0, d1);
      min = min(min, d2);
      if( min == d0 ){ target_ship = target_0; } 
      if( min == d1 ){ target_ship = target_1; } 
      if( min == d2 ){ target_ship = target_2; } 
    
      current_ship %= TWO_PI; 
    
      if(target_ship > current_ship) current_ship += 0.05;
      if(target_ship < current_ship) current_ship -= 0.05;
    
      x = int(width/2+165*cos(current_ship)); 
      y = int(height/2+165*sin(current_ship)); 
    
      pushMatrix(); 
      translate(x, y); 
      rotate(atan2( mouseY - height/2, mouseX - width/2)-PI/2); 
      triangle(-30, -10, 0, +50, +30, -10); 
      popMatrix(); 
    } 
    
  • @TfGuy44 I'm a bit late but thanks anyway!

Sign In or Register to comment.