Pre-requisite:

  1. Targeted moving

Objectives:

  1. Add some random factors to chasing the target
  2. The movement may look jitter or shaky.

Advance:

  1. Move along pre-calculated spline.

Descriptions:

  1. Assume you can move the object to the target
  2. Adding a random number to the theta will give you a more organic movement

    Source
     
    // x1, y1 are current position, x2, y2 are target positionfloat x1, y1, x2, y2;
      
    void setup(){
        size(600,400);
        // Set current position to centre
        x1 = 300;
        y1 = 200;
    	frameRate(30);
     
    	// Set the random seed so that the sequence is different each time
    	randomSeed(millis());
    }
    void draw(){
        background(0);
        fill(255);
        // Movement code here :
        x2 = mouseX;
        y2 = mouseY;
      
        float l = sqrt( pow((x2-x1),2) + pow((y2-y1),2) );
        if( l > 0.5 ){
            float theta = acos((x2-x1) / l);
    
    		// Add the random factor here
    		// The maths in processing is calculated in radians
    		// Gives it a +- 90 degrees of deviation
    		theta += radians( random( -90, 90 ) );
    
            if( y2 < y1 ){
                theta = 2 * PI - theta;
            }
            x1 += 2 * cos(theta);
            y1 += 2 * sin(theta);
        }
      
        // Draw the result
        ellipse( x1, y1, 30, 30 );
    }
    
  3. Smoothing out the movement ( You don't want to change the direction each frame so it looks jumpy )

    Source
     
     // 10 frames to change a deviation
    final int deviationframe = 10;
    int framecount = 0;
     
    // Add a global to save the random factor
    float randangle = 0;
     
    // x1, y1 are current position, x2, y2 are target positionfloat x1, y1, x2, y2;
    float x1,y1,x2,y2;
      
    void setup(){
        size(600,400);
        // Set current position to centre
        x1 = 300;
        y1 = 200;
    	frameRate(30);
     
    	// Set the random seed so that the sequence is different each time
    	randomSeed(millis());
    }
    void draw(){
        background(0);
        fill(255);
        // Movement code here :
        x2 = mouseX;
        y2 = mouseY;
      
        float l = sqrt( pow((x2-x1),2) + pow((y2-y1),2) );
        if( l > 0.5 ){
            float theta = acos((x2-x1) / l);
    
    		// Add the random factor here
    		// The maths in processing is calculated in radians
    		// Gives it a +- 90 degrees of deviation
    		// Save the angle
    		
    		if( ++framecount > deviationframe ){
    			randangle = radians( random( -90, 90 ) );
    			framecount = 0;
    		}
    		theta += randangle;
    
            if( y2 < y1 ){
                theta = 2 * PI - theta;
            }
            x1 += 2 * cos(theta);
            y1 += 2 * sin(theta);
        }
      
        // Draw the result
        ellipse( x1, y1, 30, 30 );
    }
    
  • No labels