Speed in relation to MouseY coordinate on a 2 point system

In need some help with controlling the speed of an object along a straight line. This is the basic outline of the code, and the setup i want for my simulation. I am trying create a simple environment to test some arduino prototypes with later on. All i need is a square that moves horizontally along a line and the speed can be adjusted depending on the state of an a external potentiometer input. For now I was just trying to use the relative MouseX coordinates to simulate a potentiometer. I have tried creating an object for the moving piece, which brought me a little closer, but still didn't allow me to have variable speeds, depending on the location on my finger on the trackpad. I would greatly appreciate any help on this. I have spend the last two days going through examples, tutorials, and anything i could find, without figuring out how this can be done.

Thank you-

 int dx = 1;
    float x = 100;
    float y = 100;
    float xspeed = 1;


    void setup () {
      size(1200, 300);
      smooth();
      background(#1E8FD3);
      fill(#1F8E27);
      ellipse(0, 150, 150, 150);
      ellipse(1200, 150, 150, 150);
      fill(50);
      ellipse(150, 150, 25, 25);
      ellipse(1050, 150, 25, 25);
      rect(150, 150, 900, 2);


    }

    void draw () {
      background(#1E8FD3);
      fill(#1F8E27);
      ellipse(0, 150, 150, 150);
      ellipse(1200, 150, 150, 150);
      fill(50);
      ellipse(150, 150, 25, 25);
      ellipse(1050, 150, 25, 25);
      rect(150, 149, 900, 2);
      fill (155);
      rect(x,145, 30, 10); 
      x = x + dx;
     if (x> 1000){
     dx = -1;
     }
     if(x <150) {
       dx = 1;
     }
     }
`

Any help is greatly appreciated!

Answers

  • You have a xspeed variable which you don't use. Make it dependent of an external factor (you can try mouse position for testing, then serial input). Then replace the formula

    x = x + dx;
    

    by

    x += dx * xspeed;
    

    ie. dx is just the direction, the xspeed is the amount of displacement on each frame.

  • It seems to simple now. Thank you very much for the tip, hopefully this will work.

  • I tried including the formula into my code, but it doesn't work. The square stops moving all together. I have tried several options to enter the mouse position, but none of them have worked. Any further suggestions? i think the equation should work, however the numbers coming in from mouseY are too large/small maybe. I tried mapping the mouseY which didnt work either.

  • You should show your last attempt (with mapping), so we can help you further. Sometime code fails because of simple things overlooked.

Sign In or Register to comment.