Making a line track the cursor

I'm guessing this is a fairly common question, but I need to make a line from, say, (100,100) with a length of 30 track the cursor. I tried converting to polar coordinates and back to cartesian, but I'm running into lots of errors.

Thanks

Answers

  • Answer ✓
    PVector p = new PVector(0,0,0);
    
    void setup(){
      size(400,400);
      stroke(255);
    }
    
    void draw(){
      background(0);
      p.x = mouseX - width/2;
      p.y = mouseY - height/2;
      translate(width/2,height/2);
      p.normalize();
      line(0,0,30*p.x,30*p.y);
    }
    
  • _vk_vk
    Answer ✓
    PVector origin, end;
    float range = 30;
    
    
    void setup(){
        size(300,300);
        origin = new PVector (100,100);
        end = new PVector (0,0);
        }
    
    
    void draw(){
        background(255);
        float a = atan2(mouseY - origin.y, mouseX - origin.x);
        end.x = origin.x + cos(a)*range;
        end.y = origin.y + sin(a)*range;
    
    
        line(origin.x, origin.y, end.x, end.y);
        }
    
Sign In or Register to comment.