<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
      <title>Tagged with constrain() - Processing 2.x and 3.x Forum</title>
      <link>https://forum.processing.org/two/discussions/tagged/feed.rss?Tag=constrain%28%29</link>
      <pubDate>Sun, 08 Aug 2021 19:22:21 +0000</pubDate>
         <description>Tagged with constrain() - Processing 2.x and 3.x Forum</description>
   <language>en-CA</language>
   <atom:link href="/two/discussions/taggedconstrain%28%29/feed.rss" rel="self" type="application/rss+xml" />
   <item>
      <title>Collision between object moved by keys and random object</title>
      <link>https://forum.processing.org/two/discussion/28106/collision-between-object-moved-by-keys-and-random-object</link>
      <pubDate>Tue, 28 Aug 2018 01:15:35 +0000</pubDate>
      <dc:creator>rmar15</dc:creator>
      <guid isPermaLink="false">28106@/two/discussions</guid>
      <description><![CDATA[<p>Hello, I'm having problems with this collision thingy between the 2 rectangles, I know I'm supposed to use dist(), It worked when my object was controlled by mouse, but I can't make it work now with keys, any help would be appreciated! :)</p>

<pre><code>Ship myShip;
int a=1;
int b=100;
int c=200;
int d=300;
int e=400;
int f=500;
int z=10;
int j=160;
boolean [] keys = new boolean[128];


void setup() {
  size(500, 600); 
  smooth();
  myShip = new Ship();
}
void gameOver() {
    textAlign(CENTER);
    text("GAME OVER", width / 2, height / 2);

    }

void draw() {
  background(0);
  a=a+3;
  b=b+3;
  c=c+3;
  d=d+3;
  e=e+3;
  f=f+3;
  z=z+4;
  rect(j,z+3,25,25);
  rect(270,a+3,5,30);
  rect(270,b,5,30);
  rect(270,c,5,30);
  rect(270,d,5,30);
  rect(270,e,5,30);
  rect(270,f,5,30);
  rect(80,0,5,1500);
  if (a&gt;=600)
  a=-10;
  if (b&gt;=600)
  b=-10;
  if (c&gt;=600)
  c=-10;
  if (d&gt;=600)
  d=-10;
  if (e&gt;=600)
  e=-10;
  if (f&gt;=600)
  f=-10;
  myShip.run();
}

void keyPressed() {
  keys[key] = true;
}

void keyReleased() {
  keys[key] = false;
}


class Ship {  
  PVector pos, vel;
  float rotation;


  Ship() {
    pos = new PVector(160, height/2);
    vel = new PVector(5, 5);
    rotation = 0;
  }

  void run() {    //generic function container
    display();
    move();
  }


  void display() {
    pos.x=constrain(pos.x, 25, width);
    pos.y=constrain(pos.y, 25, height);
    pushMatrix();
    translate(pos.x, pos.y);
    rect(0, 0, 50, 50);
    popMatrix();
   if (pos.x&gt;=260) 
  noLoop();
  if (pos.x&lt;=60) 
  noLoop();
  if (pos.x&gt;=260)
  gameOver();
    if (pos.x&lt;=60)
  gameOver();
  if (dist(pos.x,pos.y,50,a+1)&lt;25)
  noLoop();


  }


  void move() {
    if (keys['a']) //move left 
      pos.x -= vel.x;
    if (keys['d']) //move right
      pos.x += vel.x;
    if (keys['w']) //move up
      pos.y -= vel.y;
    if (keys['s']) //move down
      pos.y += vel.y;

  }

}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Interactivity</title>
      <link>https://forum.processing.org/two/discussion/26411/interactivity</link>
      <pubDate>Sat, 17 Feb 2018 21:01:19 +0000</pubDate>
      <dc:creator>byurur</dc:creator>
      <guid isPermaLink="false">26411@/two/discussions</guid>
      <description><![CDATA[<p>Hi everyone</p>

<p>I need help to add interactivity to a work I've done, can you help me with this?</p>

<pre><code>class Particle {

  PVector location;
  PVector velocity;
  PVector acceleration;
  PVector force,friction;
  float mass,r,distance,loc;
  float maxForce, maxSpeed,strength;
  int id,val;
  color c;
  float k = 0.02;
  int age = 0;
  int spawnAge = (int)random(80,120);
  float minr = 0;
  float maxr = 5.0;
  boolean spawned = false;

  Particle(float x, float y,int _id) {
    mass = 0.1;
    id = _id;
    r = 0.1;
    maxSpeed = 1;
    maxForce = 10;
    location = new PVector(constrain(x,r,width-r), constrain(y,r,height-r));
    velocity = new PVector(0, 0);
    acceleration = new PVector(0, 0);
  }

  void applyForce(PVector force) {
    //PVector f = PVector.div(force, mass);
    acceleration.add(force);
  }

  void update() {
    velocity.add(acceleration);
    velocity.limit(maxSpeed);
    location.add(velocity);
    acceleration.mult(0);
    friction();
    borders();
    age+=1;
  }

  void friction(){
     friction = velocity.copy();
     friction.mult(-1);
     friction.normalize();
     friction.mult(k);

     applyForce(friction);
  }

  void display() {

    ellipse(location.x,location.y,r*2,r*2);
  }

  PVector attract(Particle p) {
    force = PVector.sub(p.location,location);
    distance = force.magSq(); 

      distance = constrain(distance, 1.0, 5000.0);
      force.normalize();

      strength = (g) / (distance*4*PI);
      force.mult(strength);n
      return force;


  }

  void setRadius (PImage img){

      loc = (int)location.x + (int)location.y*img.width;
      //c= img.get((int)location.x,(int)location.y);
      //c =  img.pixels[int(loc)];
      val = img.pixels[int(loc)] &amp; 0xFF;
      r=  lerp(r,map(val,0.0,255.0,minr,maxr),0.01);

  }

  void borders() {
      if ( location.x &lt; r || location.x &gt; width-r){
          velocity.x = -velocity.x;
      }
      if ( location.y &lt; r || location.y &gt; height-r){
          velocity.y = -velocity.y;
      }

      if (location.x&gt; width-r) location.x = width-r;
      if (location.x&lt; r) location.x = r;
      if (location.y&gt; height-r) location.y = height-r;
      if (location.y&lt; r) location.y = r;

  }

}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Got Error in Constrain</title>
      <link>https://forum.processing.org/two/discussion/25378/got-error-in-constrain</link>
      <pubDate>Mon, 04 Dec 2017 17:06:27 +0000</pubDate>
      <dc:creator>2DK</dc:creator>
      <guid isPermaLink="false">25378@/two/discussions</guid>
      <description><![CDATA[<p>Hi, I'm quite new in Processing.py, so this can be a damn question, but I'm confused using constrain. When I use constrain with three variables; constrain(mouseX,10,width - 10), it will return error that "TypeError: 'int' object is not callable". Is there someone who know how to fix it?</p>
]]></description>
   </item>
   <item>
      <title>how to draw moved triangle?</title>
      <link>https://forum.processing.org/two/discussion/24710/how-to-draw-moved-triangle</link>
      <pubDate>Mon, 23 Oct 2017 15:53:38 +0000</pubDate>
      <dc:creator>Adam89z</dc:creator>
      <guid isPermaLink="false">24710@/two/discussions</guid>
      <description><![CDATA[<p>Hello,</p>

<p>I am studying IT at an university in the Netherlands. We got an assignment in which we need to create a run. In this run there will be two to fourteen triangles competing each other. The goal of this game is that all the triangles will move separately by using the dice. However, they move all at the same time. The second issue is that once all the triangles passed the finish line, there should come up a box with the overal score (from first up to the last place).</p>

<p>Is there anyone who could help me with these two issues?</p>

<p>Please find below the codes.</p>

<p>Thanking you in advance.</p>

<pre><code>int numberOfTriangles;
int margin;
float y = 0;
boolean startGame = false;


void setup() {
  // background(0);
  size(600, 600);
}


void draw() {


  background(0);
  if (startGame) {
    drawButton(" STOP", width-width/5, height/40, width/6, height/17);
    drawLines();
    printTexts();

    moveTriangles();
  } else {
    drawButton(" START", width-width/5, height/40, width/6, height/17);
    printTexts();
    drawLines();
    drawTriangles();
    drawSliderNumbers(width/4, height/40, width/12, height/60, 15);
   drawSliderMargin(width/20, height/40, width/12, height/60, width/3);
  }
}

void moveTriangles() {

  int p =width/120;

  float space = margin * (numberOfTriangles+1);   
  float sidesNumbers = width- space;
  float side = sidesNumbers /numberOfTriangles; 



  float x1=0;
  float x2=0;
  float x3=0;
  float y1 = height-height/20 -p;
  float y2 =height-height/20 -p;
  float y3 = height-height/20-p-side;

  float players[][] = {{x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, 
    {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, 
    {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, 
    {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, 
    {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, };

  int i = 0;
  while (i&lt; numberOfTriangles) {
    players[i][0] =(side*i)+((i+1)*margin);
    players[i][2] = players[i][0] + side;
    players[i][4] = players[i][2] - (side/2);
    i++;
  }

  if (side&lt;25 ||side&gt;70) {

    fill(255);
    textSize(width/30);
    textAlign(CENTER, CENTER);
    text("game can't start with this margin", width/2, height/2);
  } else {
    i=0;
    while (i&lt; numberOfTriangles) {
      fill(random(255), random(255), random(255));
      triangle(players[i][0], y1-y, players[i][2], y2-y, players[i][4], y3-y);
      fill(random(255), random(255), random(255));
      textAlign(CENTER, BOTTOM);
      text(i+1, players[i][4], y1-y);


      i++;
    }
    y++;

    y=constrain(y, 0, (height/1.33));
    println(mouseY);
  }
}

    void drawLines() {
      stroke(255, 0, 0);
      line(0, height/5, width, height/5);       //finish
      line(0, height - height/20, width, height - height/20);     //start
    }

    void printTexts() {
      theTexts("numberOfTriangles: " + numberOfTriangles, width/4, height/25);

      theTexts("margin : " + margin, width/20, height/25);
      theTexts("Finish Line", 0, height/5);
      theTexts("Start Line", 0, height - height/20);

    }

    String theTexts(String text, int x, int y) {
      fill(255);
      textSize(width/40);
      textAlign(LEFT, TOP);
      text(text, x, y);
      return text;
    }




    void drawButton(String notification,int x , int y, int Width , int Height) {


      fill (#00FF00);    
      rect(x, y, Width, Height);
      textSize(width/20);
      fill (0);        
      textAlign(CENTER, CENTER);
      text ( notification, width-width/8, height/20) ;
    }


    void mouseClicked() {
      int x = width-width/5;
      int y=height/40;
      int Width = width/6;
      int Height=height/17;

      if ( mouseX &gt; x  &amp;&amp; mouseX &lt; x + Width
        &amp;&amp; mouseY &gt; y &amp;&amp; mouseY&lt; y + Height ) {
        startGame = ! startGame;
      }
    }

void drawTriangles() {
  int p =width/120;

  float space = margin * (numberOfTriangles+1);   //de lege afstand tussen de driehoeken
  float sidesNumbers = width- space;
  float side = sidesNumbers /numberOfTriangles; 

  float x1=0;
  float x2=0;
  float x3=0;
  float y1 = height-height/20 -p;
  float y2 =height-height/20 -p;
  float y3 = height-height/20-p-side;

  float players[][] = {{x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, 
    {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, 
    {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, 
    {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, 
    {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, {x1, y1, x2, y2, x3, y3}, };


  int i = 0;
  while (i&lt; numberOfTriangles) {
    players[i][0] =(side*i)+((i+1)*margin);
    players[i][2] = players[i][0] + side;
    players[i][4] = players[i][2] - (side/2);
    i++;
  }

  if (side&lt;25 ||side&gt;60) {

    fill(255);
    textSize(width/30);
    textAlign(CENTER, CENTER);
    text("game can't start with this margin", width/2, height/2);
    // text("side = " +side, width/2, height/3);
  } else {
    i=0;
    while (i&lt; numberOfTriangles) {
      fill(random(255), random(255), random(255));
      triangle(players[i][0], y1, players[i][2], y2, players[i][4], y3);
      fill(random(255), random(255), random(255));

      textAlign(CENTER, BOTTOM);
      text(i+1, players[i][4], y1);


      i++;
    }
  }
}

void drawSliderNumbers(float x, float y, float Width, float Height, int nPosition) {
  float cubeWidth= Width/nPosition;
  int position ;

  //println(floor((mouseX - x) / cubeWidth)); 

  if (mouseX&gt;=x &amp;&amp; mouseX&lt; x + Width &amp;&amp; mouseY&gt;= y &amp;&amp; mouseY&lt;=y +Height) {
    position = floor(((mouseX -x) / cubeWidth));
    numberOfTriangles = position  ;
  } else {
    position  = numberOfTriangles ;
    numberOfTriangles =constrain(numberOfTriangles, 2, 14);
  }

  noStroke();
  fill(255);
  rect(x, y, Width, Height);

  fill(#2257F0);
  rect(x + position * cubeWidth, y, cubeWidth, Height);
}

void drawSliderMargin(float x, float y, float Width, float Height, int nPosition) {
  float cubeWidth= Width/nPosition;
  int position ;

  //println(floor((mouseX - x) / blokjeBreedte)); // we maken Nposities om te bepalen hoeveel rect we willen,ipv delen door een getaal hier

  if (mouseX&gt;=x &amp;&amp; mouseX&lt; x + Width &amp;&amp; mouseY&gt;= y &amp;&amp; mouseY&lt;=y +Height ) {
    position = floor((mouseX - x) / cubeWidth);
    margin = position +2  ;
  } else {
    position = margin ;
    margin=constrain(margin, 2, width/3);
  }
  noStroke();
  fill(255);
  rect(x, y, Width, Height);
  fill(255, 0, 0);
  rect(x + position * cubeWidth, y, cubeWidth, Height);
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>How do I constrain an image that moves via mouseY ?</title>
      <link>https://forum.processing.org/two/discussion/24679/how-do-i-constrain-an-image-that-moves-via-mousey</link>
      <pubDate>Sat, 21 Oct 2017 17:11:02 +0000</pubDate>
      <dc:creator>Lukas1</dc:creator>
      <guid isPermaLink="false">24679@/two/discussions</guid>
      <description><![CDATA[<p>Hello</p>

<p>First post, first use of processing, level basic, code fudged...</p>

<p>I'm trying to get the equivalent of a flag to run up a flagpole via mouseY but want to stop the image at the bottom and top. What metalanguage should I be searching for to help me to do this?
Code posted below so far, (one flag image is replaced with another)</p>

<p>Thanks</p>

<p>Lukas</p>

<pre><code>PImage field;
PImage flag;
PImage whiteflag;

void setup() {

  size(600, 399); // size of field file is size of window for now
  flag = loadImage("flag.jpg");  // Load the image
  field = loadImage("fieldnpole.jpg");  // Load the image
  whiteflag = loadImage("whiteflag.jpg");  // Load the image
}


void draw() {
  background(0);
  tint(255, 255);


  image(field, 0, 0);


  image(whiteflag, 125, mouseY, 200, 100);

  tint(255, 255, 255, mouseY);
  image(flag, 125, mouseY, 200, 100);
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>How to have an object Stay Inside Canvas ?</title>
      <link>https://forum.processing.org/two/discussion/23748/how-to-have-an-object-stay-inside-canvas</link>
      <pubDate>Tue, 08 Aug 2017 18:42:17 +0000</pubDate>
      <dc:creator>bloomboy</dc:creator>
      <guid isPermaLink="false">23748@/two/discussions</guid>
      <description><![CDATA[<p>I am trying to make my object stay within the canvas boundaries, its not working! I haven't a clue why.. any ideas?</p>

<pre><code>Wanderer[] wanderer = new Wanderer[1];

void setup()
{
 size(1280, 720);
 background(0);
 fill(250);
 noStroke();

 for (int i=0; i&lt;wanderer.length; i++)
 {
   wanderer[i] = new Wanderer(random(width), random(height));
 }
}

void draw()
{
 background(0);

 for (int i=0; i&lt;wanderer.length; i++)
 {
   wanderer[i].stayInsideCanvas();
   wanderer[i].move();
   ellipse(wanderer[i].getX(), wanderer[i].getY(), 50, 50);
 }
}
class Wanderer
{
 float x;
 float y;
 float wander_theta;
 float wander_radius;

 // bigger = more edgier, hectic
 float max_wander_offset = 0.3;
 // bigger = faster turns
 float max_wander_radius = 20.5;

 Wanderer(float _x, float _y)
 {
   x = _x;
   y = _y;

   wander_theta = random(TWO_PI);
   wander_radius = random(max_wander_radius);
 }

 void stayInsideCanvas()
 {
   x %= width;
   y %= height;
 }

 void move()
 {
   float wander_offset = random(-max_wander_offset, max_wander_offset);
   wander_theta += wander_offset;

   x += cos(wander_theta);
   y += sin(wander_theta);
 }

 float getX()
 {
   return x;
 }

 float getY()
 {
   return y;
 }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Set min Canvas Size</title>
      <link>https://forum.processing.org/two/discussion/23233/set-min-canvas-size</link>
      <pubDate>Tue, 27 Jun 2017 18:14:45 +0000</pubDate>
      <dc:creator>Alivanar</dc:creator>
      <guid isPermaLink="false">23233@/two/discussions</guid>
      <description><![CDATA[<p>Hi there,
I was wondering if it was possible to set a minimal size for the canvas ? Here is the code i want to use :</p>

<pre><code>window.onresize = function() {
  if(c.width &gt;= 600){
    c.size(window.innerWidth, c.height);
  }
  if(c.height &gt;= 400){
    c.size(c.width, window.innerHeight);
  }
}
</code></pre>

<p>But i have some strange behavior : when i reduce the size of the window it works and limits the canvas size, but after that if i want to expand the window the sketch's size won't change anymore .... I guess i'm mistaking somewhere but can't see where ... Do you have any idea ?</p>

<p>Thanks</p>
]]></description>
   </item>
   <item>
      <title>How to make 2 moving images collide?</title>
      <link>https://forum.processing.org/two/discussion/22966/how-to-make-2-moving-images-collide</link>
      <pubDate>Tue, 06 Jun 2017 23:47:15 +0000</pubDate>
      <dc:creator>brianna0811</dc:creator>
      <guid isPermaLink="false">22966@/two/discussions</guid>
      <description><![CDATA[<p>I want to have the panda (which the user moves with left and right arrow keys) collide with a candy image which is falling from the top left of the screen. When the 2 images collide, it would say "YOU TOUCHED THE CANDY" on the screen and the console. But when the panda and candy touch, nothing happens.</p>

<p>Here is the link to the code (I couldn't figure out how to indent the code on here):
<a href="https://paste.ofcode.org/sBSTST866aqUv5xkzWJ84g" target="_blank" rel="nofollow">https://paste.ofcode.org/sBSTST866aqUv5xkzWJ84g</a></p>

<p>I tried doing if (pandaX==xPosCandy &amp;&amp; pandaY==yPosCandy ) 
But it didn't work.
I also tried doing if (pandaX&gt;xPosCandy &amp;&amp; pandaY&lt;yPosCandy ) but it says YOU TOUCHED THE CANDY too soon.</p>

<p>Any help would be appreciated, and let me know if you need more code. Thanks!</p>
]]></description>
   </item>
   <item>
      <title>How to set a range of values in an array?</title>
      <link>https://forum.processing.org/two/discussion/21865/how-to-set-a-range-of-values-in-an-array</link>
      <pubDate>Thu, 06 Apr 2017 19:54:23 +0000</pubDate>
      <dc:creator>john832</dc:creator>
      <guid isPermaLink="false">21865@/two/discussions</guid>
      <description><![CDATA[<p>I have an array float[] positionx = new float[100]. I want to be able to add 1 to all of the values in that array from 0 to a certain variable (let's say its value is 50). I don't want to do positionx[0] = positionx[0] + 1, positionx[1] = positionx[1] + 1, and so on all the way to 50. Is there a simpler way to do it? Something like positionx[0 through X] = positionx[0 through X] + 1</p>
]]></description>
   </item>
   <item>
      <title>Matter.js Collision Not Detecting</title>
      <link>https://forum.processing.org/two/discussion/21409/matter-js-collision-not-detecting</link>
      <pubDate>Wed, 15 Mar 2017 12:18:16 +0000</pubDate>
      <dc:creator>pyan83</dc:creator>
      <guid isPermaLink="false">21409@/two/discussions</guid>
      <description><![CDATA[<p>I'm trying to practice using matter.js to create top down levels Bomberman/Zelda style.</p>

<p>Right now I want to get my circle, which is controlled by arrow keys to move and bump into static squares but it is just going through them. Did I set it up incorrectly? I have been coding for three months, so I might be quite slow sorry!</p>

<pre><code>var Engine = Matter.Engine,
    World = Matter.World,
    Bodies = Matter.Bodies;

var engine = Engine.create();
var world = engine.world;

var player;
var rocks = [];
var cols = 7;
var rows = 7;

function setup() {
    createCanvas(750, 750);
    Engine.run(engine);

    player = new Player(300, 300, 25);

    var spacing = width / cols;
    for (var j = 0; j &lt; rows; j++) {
        for (var i = 0; i &lt; cols; i++) {
            var r = new Rocks(i * spacing, j * spacing);
            rocks.push(r);
        }
    }
}

function draw() {
    background(51);
    Engine.update(engine);
    for (var i = 0; i &lt; rocks.length; i++) {
        rocks[i].show();
    }
    player.show();
    player.move();
}

function Player(x, y, r) {
    this.body = Bodies.circle(x, y, r);
    this.r = r;
    World.add(world, this.body);

    this.show = function () {
        ellipse(x, y, this.r * 2);
    }

    this.move = function () {
        if (keyIsDown(RIGHT_ARROW))
            x += 10;
        if (keyIsDown(LEFT_ARROW))
            x -= 10;
        if (keyIsDown(UP_ARROW))
            y -= 10;
        if (keyIsDown(DOWN_ARROW))
            y += 10;
        x = constrain(x, this.r, height - this.r);
        y = constrain(y, this.r, width - this.r);
    }
}

function Rocks(x, y, w, h, options) {
    var options = {
        isStatic: true
    }
    this.body = Bodies.rectangle(x, y, h, w, options);
    this.w = w;
    this.h = h;
    this.size = player.r * 2;
    World.add(world, this.body);

    this.show = function () {
        rect(x, y, this.size, this.size);
    }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>minim: 1st clip doesn't play on 1st play()</title>
      <link>https://forum.processing.org/two/discussion/19651/minim-1st-clip-doesn-t-play-on-1st-play</link>
      <pubDate>Sat, 10 Dec 2016 20:04:25 +0000</pubDate>
      <dc:creator>pop451</dc:creator>
      <guid isPermaLink="false">19651@/two/discussions</guid>
      <description><![CDATA[<p>In my simple picture dictionary code cited below, I add the last line in setup() [line 29], i.e. preload the 1st sound clip, or else it doesn't play on 1st instance of play().</p>

<p>I guess this is not the best solution. Any advice?</p>

<pre><code>import ddf.minim.spi.*;
import ddf.minim.signals.*;
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.ugens.*;
import ddf.minim.effects.*;
Minim minim;
AudioPlayer player;

PImage image, imageSprite;
int sX, sY, eX, eY ;
XML fruitList ;
XML[] fruits ;
int click;
String name, thisPage, startMessage;

void setup() {
  size(600, 400) ;
  minim = new Minim(this);
  click = 0 ;
  name ="";
  thisPage = "";

  image = loadImage("fruits.jpg") ;
  fruitList = loadXML("fruitList.xml") ;
  fruits = fruitList.getChildren("fruit") ;
  startMessage = "In this lesson, you will learn " + fruits.length + " words.\nLeft-click to start &amp; go next. \nRight-click to go back." ;

  player = minim.loadFile("0.mp3", 2048); // to preload the initial sound clip
}

void draw() {
  if (click == 0) {
    background(255) ;
    textSize(20);
    fill(0);
    text(startMessage, width/2 - textWidth(startMessage)/2, height/2 - 40);
  } else {
    background(255) ;
    name = fruits[click-1].getChild("name").getContent();
    fill(0);
    textSize(40);
    text(name, width/2 - textWidth(name)/2, 60);


    sX = int(fruits[click-1].getChild("get/sX").getContent());
    sY = int(fruits[click-1].getChild("get/sY").getContent());
    eX = int(fruits[click-1].getChild("get/eX").getContent());
    eY = int(fruits[click-1].getChild("get/eY").getContent());
    imageSprite = image.get(sX, sY, eX - sX, eY - sY);
    image(imageSprite, width/2 - imageSprite.width/2, height/2 - imageSprite.height/2) ;

    thisPage = click + "/" + fruits.length ;
    fill(127);
    textSize(20);
    text(thisPage, width - textWidth(thisPage), height -25);
  }
}

void mouseClicked () {
  if (mouseButton == LEFT) {
    click++ ;
  } else if (mouseButton == RIGHT) {
    click-- ;
  }
  click = constrain(click, 1, fruits.length);

  player = minim.loadFile(click-1 + ".mp3", 2048); // 1024, 2048
  player.setGain(-20);
  player.play();
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Make Balls/Circles bounce off canvas doesn't work</title>
      <link>https://forum.processing.org/two/discussion/19384/make-balls-circles-bounce-off-canvas-doesn-t-work</link>
      <pubDate>Tue, 29 Nov 2016 09:03:43 +0000</pubDate>
      <dc:creator>Slothside</dc:creator>
      <guid isPermaLink="false">19384@/two/discussions</guid>
      <description><![CDATA[<p>Hey guys,</p>

<p>I got this sketch here : <a href="https://www.openprocessing.org/sketch/391671" target="_blank" rel="nofollow">https://www.openprocessing.org/sketch/391671</a>
I want the Circles to bounce of the walls. I made an if statement inside "this.update" to make the circles bounce off the left and right of the canvas, but it doesn't work. Also i'd like the circles to bounce of each other.</p>

<pre><code>var fly;
var sam;

function setup() {
    createCanvas(900,600);
    background(100);
    fly = new Bug(width/2,height/2);
    sam = new Bug(100,250);
}

function draw() {



    fly.update();
    fly.draw();


    sam.update();
    sam.draw();

}

function Bug(startX,startY) {
    this.x = startX;
    this.y = startY;
    this.diameter = random(10,100);
    this.speed = random(2,10);

    this.draw = function(){ 
        fill(55);
        stroke(255);
        ellipse(this.x,this.y,this.diameter,this.diameter);
    }

    this.update = function() {
        this.x += random(-this.speed,this.speed);
        this.y += random(-this.speed,this.speed);

        if (this.x &gt; 200){
            this.speed = this.speed * -1;
            console.log("out of canvas right")
        }
        if (this.x &lt; 200){
            this.speed = this.speed;
            console.log("out of canvas left")
        }

    }
}
    /*this.bounce = function() {
        if (this.x &gt;= width || this.x &lt;= width){
        this.speed *= -1;
        console.log("test");
    } 

    }*/
</code></pre>
]]></description>
   </item>
   <item>
      <title>Set minimum and max range in relation to window size</title>
      <link>https://forum.processing.org/two/discussion/18527/set-minimum-and-max-range-in-relation-to-window-size</link>
      <pubDate>Thu, 13 Oct 2016 05:31:49 +0000</pubDate>
      <dc:creator>bzhang</dc:creator>
      <guid isPermaLink="false">18527@/two/discussions</guid>
      <description><![CDATA[<p><code>final float MAX_SIZE = 35000;
final float MIN_SIZE = MAX_SIZE/10;
float alienSize;
float alienY;
float alienX;
void draw()
{
    alienX = mouseX;
    alienY = mouseY;
    alienSize = MAX_SIZE*mouseY/height;
}</code></p>

<p>My goal is to make the variable alienSize be the max size when it ( and the mouse ) is at the bottom of the window and 1/10th the size when it ( and the mouse ) is at the top of the window. I have so far this code which works for the max size but there is no limit to how small the alien can get. any help please :)</p>

<p>Edit: I have to hand this in so no cheating please like having an if statement check for the size or anything</p>
]]></description>
   </item>
   <item>
      <title>Processing code doesn't work in p5</title>
      <link>https://forum.processing.org/two/discussion/18404/processing-code-doesn-t-work-in-p5</link>
      <pubDate>Tue, 04 Oct 2016 14:52:03 +0000</pubDate>
      <dc:creator>Mskelly</dc:creator>
      <guid isPermaLink="false">18404@/two/discussions</guid>
      <description><![CDATA[<p>Hello everybody,
I am new here and quite intimidated by all the wonderful work that is done here. I'm a a student and just discovering Processing. For a project I downloaded p5 because I'd like to run my files online. I've managed to do the transfer with my sketches from the normal processing code to p5.js, except for one, and I just can't figure out why it won't work. It's with the 'constrain' function, where I'd like to limit a dot (mouse coordinates) to a rectangle in the sketch, if that makes any sense. I copy both the codes here, hoping that someone can help me! Thank you for taking the time to read this.</p>

<p><strong>Original code Processing:</strong></p>

<p>float mx;
float my;
float easing = 0.05;
int radius = 10;
int edge = 235;
int inner = edge + radius;
void setup() {
  size(500, 700);
  noStroke(); 
  ellipseMode(RADIUS);
  rectMode(CORNERS);
  }</p>

<p>void draw() {</p>

<p>if (abs(mouseX - mx) &gt; 0.1) {
    mx = mx + (mouseX - mx) * easing;
  }
  if (abs(mouseY - my) &gt; 0.1) {
    my = my + (mouseY- my) * easing;
  }</p>

<p>mx = constrain(mx, inner, width - inner);
  my = constrain(my, inner, height - inner);
  fill(196, 239, 234);
  rect(edge, edge, width-edge, height-edge);
  fill(146, 140, 211);<br />
  ellipse(mx, my, radius, radius);
}</p>

<p><strong>Code that I typed in p5:</strong></p>

<p>var mx;
var my;
var easing = 0.05;
var radius = 10;
var edge = 120;
var inner = edge + radius;</p>

<p>function setup() {
  createCanvas(windowWidth, windowHeight);
  noStroke();
   background(255,255,255)
  ellipseMode(RADIUS);
  rectMode(CORNERS);
}</p>

<p>function draw() {</p>

<p>if (abs(mouseX - mx) &gt; 0.1) {
    mx = mx + (mouseX - mx) * easing;
  }
  if (abs(mouseY - my) &gt; 0.1) {
    my = my + (mouseY- my) * easing;
  }</p>

<p>x= constrain(mx, inner, width - inner);
  y= constrain(my, inner, height - inner);
  fill(196, 239, 234);
  rect(edge, edge, width-edge, height-edge);
  fill(146, 140, 211);<br />
  ellipse(mx, my, radius, radius);</p>

<p>}</p>
]]></description>
   </item>
   <item>
      <title>sending data from arduino to processing</title>
      <link>https://forum.processing.org/two/discussion/17981/sending-data-from-arduino-to-processing</link>
      <pubDate>Fri, 26 Aug 2016 20:10:33 +0000</pubDate>
      <dc:creator>afroginacup</dc:creator>
      <guid isPermaLink="false">17981@/two/discussions</guid>
      <description><![CDATA[<p>Hi I am working on my arduino project and am trying to send ultrasonic sensor data and pulse sensor data to processing.
I've already put sound file to processing but I want the "heartbeat.mp3" file to be played whenever pulse is detected. I tried putting 'QS == true' and other ways like that, but I still have not figured out.</p>

<p>Also once I get the sound file play according to the pulse I would like to control the volume of it with data received by ultrasonic sensors. Like getting louder when the distance gets closer.</p>

<p>I'm a total beginner and just so confused how I should put code for both programs. Help me and thanks!</p>

<p>My arduino code :</p>

<p>//  Variables
int pulsePin = 0;                 // Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 13;                // pin to blink led at each beat
int fadePin = 5;                  // pin to do fancy classy fading blink at each beat
int fadeRate = 0;                 // used to fade LED on with PWM on fadePin</p>

<p>// Volatile Variables, used in the interrupt service routine!
volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // int that holds the time interval between beats
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat". 
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.</p>

<p>// Regards Serial OutPut
static boolean serialVisual = false;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse</p>

<h1>define trigPin1 12</h1>

<h1>define echoPin1 11</h1>

<h1>define trigPin2 3</h1>

<h1>define echoPin2 2</h1>

<p>long duration, distance, RightSensor, LeftSensor;</p>

<p>void setup(){
  pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!
  pinMode(fadePin,OUTPUT);          // pin that will fade to your heartbeat!
  Serial.begin(115200);             // we agree to talk fast!
  interruptSetup();</p>

<p>Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);</p>

<p>void loop(){</p>

<pre><code>serialOutput() ;       
</code></pre>

<p>if (QS == true){     // A Heartbeat Was Found
                       // BPM and IBI have been Determined
                       // Quantified Self "QS" true when arduino finds a heartbeat
        fadeRate = 255;         // Makes the LED Fade Effect Happen
                                // Set 'fadeRate' Variable to 255 to fade LED with pulse
        serialOutputWhenBeatHappens();   // A Beat Happened, Output that to serial.<br />
        QS = false;                      // reset the Quantified Self flag for next time<br />
  }</p>

<p>ledFadeToBeat();                      // Makes the LED Fade Effect Happen 
  delay(20);                             //  take a break</p>

<p>SonarSensor(trigPin1, echoPin1);
RightSensor = distance;
SonarSensor(trigPin2, echoPin2);
LeftSensor = distance;</p>

<p>Serial.print(LeftSensor);
Serial.print(" - ");
Serial.print(RightSensor);
Serial.print(" - ");</p>

<p>}</p>

<p>void SonarSensor(int trigPin,int echoPin)
{ 
  digitalWrite(trigPin, LOW);
  delayMicroseconds(500);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(500);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
}</p>

<p>void ledFadeToBeat(){
    fadeRate -= 15;                         //  set LED fade value
    fadeRate = constrain(fadeRate,0,255);   //  keep LED fade value from going into negative numbers!
    analogWrite(fadePin,fadeRate);          //  fade LED
  }</p>

<p>+++</p>

<p>My processing code :</p>

<p>import processing.serial.*;
import processing.sound.*;</p>

<p>Serial myPort;</p>

<p>SoundFile file;</p>

<p>int number_of_swallowed;
int Sensor;      // HOLDS PULSE SENSOR DATA FROM ARDUINO
int IBI;         // HOLDS TIME BETWEN HEARTBEATS FROM ARDUINO
int BPM;         // HOLDS HEART RATE VALUE FROM ARDUINO necessary?</p>

<p>int trigPin1;
int echoPin1;
int trigPin2;
int echoPin2;</p>

<p>int pulsePin = 0;                 // Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 13;                // pin to blink led at each beat
int fadePin = 5;                  // pin to do fancy classy fading blink at each beat
int fadeRate = 0;                 // used to fade LED on with PWM on fadePin
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat". 
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.</p>

<p>boolean beat = false;    // set when a heart beat is detected, then cleared when the BPM graph is advanced</p>

<p>// SERIAL PORT STUFF TO HELP YOU FIND THE CORRECT SERIAL PORT</p>

<p>/*
String serialPort;
 String[] serialPorts = new String[Serial.list().length];
 boolean serialPortFound = false;
 */</p>

<p>void setup() {
  size(400, 200);</p>

<p>myPort = new Serial(this, "COM6", 9600);
  myPort.bufferUntil('\n'); // Trigger a SerialEvent on new line
  //myPort = new Serial(this, "COM6", 9600);//
  //myPort.buffer(1);//?</p>

<p>// Load a soundfile from the /data folder of the sketch and play it back
  file = new SoundFile(this, "whalesound.mp3");
  file.play();</p>

<p>if (QS == true);
  {
    file = new SoundFile(this, "heartbeat.mp3");
    file.play();
  }
}</p>

<p>void draw()
{
  background(0);
  textSize(50);
  text(number_of_swallowed +" swallowed", 50, 100);
}</p>

<p>void mouseReleased() {
  if (mouseButton == LEFT) { 
    number_of_swallowed++;
  } else { 
    number_of_swallowed = 0;
  }
}</p>
]]></description>
   </item>
   <item>
      <title>Constrain() and using arrow keys</title>
      <link>https://forum.processing.org/two/discussion/16916/constrain-and-using-arrow-keys</link>
      <pubDate>Tue, 31 May 2016 15:22:31 +0000</pubDate>
      <dc:creator>j_vanz</dc:creator>
      <guid isPermaLink="false">16916@/two/discussions</guid>
      <description><![CDATA[<p>Im trying to make a system where the following occurs;</p>

<p>a float constrained between -2 and 2 is used to define certain states</p>

<p>i.e -2 will print W, -1 will print SW, 0 will print E, 1 will print SE and two will print E</p>

<p>using conditionals, the program will print according to which state its at (for example , no key = 0, if left key is hit, state becomes -1, if hit again its -2 and cannot go past. if you want a positive you must hit the opposite key (from -2 to 2, the right arrow key must be hit 4 times) and vice versa from 2 to -2.</p>

<pre><code>float state = 0;

void setup(){
  size(500,500);
  constrain(state,-2,2);
}

void draw(){
  background(255);
  fill(0);
  textSize(32);
  numberControl();
}

void numberControl(){
  if (keyPressed ==true &amp;&amp; key == CODED &amp;&amp; keyCode == LEFT){
    state--;
    constrain(state + 1,-2,2);
    if (constrain(state + 1,-2,2) == -1){
      text(""+ constrain(state + 1,-2,2), width/2,height/2);
    }
  }
}
</code></pre>

<p>I have gotten to the 1st part and It goes past the boundary set and loops. I know draw continually loops but I cannot think how to achive what im trying to do without calling the numberControl method in draw. Any Suggestions?</p>
]]></description>
   </item>
   <item>
      <title>still struggling with bounding to screen and score board</title>
      <link>https://forum.processing.org/two/discussion/16546/still-struggling-with-bounding-to-screen-and-score-board</link>
      <pubDate>Wed, 11 May 2016 18:54:15 +0000</pubDate>
      <dc:creator>jonnyboii2</dc:creator>
      <guid isPermaLink="false">16546@/two/discussions</guid>
      <description><![CDATA[<p>so I asked a question earlier and I fixed the fact that both players were not able to move at the same time but now I cant get 
both players to stay in their own side of the game if anyone could explain how to do it I am little slow please and thank you
If someone could also point me in a direction on how to implement a score board would be greatly appreciated</p>

<pre><code>          Player Player1;
            Player Player2;
            float x = 300;
            float y = 200;
            float xspeed = 1;
            float yspeed = 3.3;
            float PlayerSpeed =10;
            float x0 = 200;// falling ball
            float y0 = 0;//^
            float y0_speed=5;//^
            int score=0;
            float xPos;
            float yPos;
            float speed;
            boolean moveLeft, moveRight, moveLeft1, moveRight1;

            void setup() {
            size(600, 400);
            background(55);
            Player1 = new Player(color(255), 137, 369, 2);
            Player2 = new Player(color(255), 452, 369, 2);
            speed = 8;
            moveLeft = moveRight = moveLeft1 = moveRight1 = false;
            }
            void draw() {
            println (mouseX +"," + mouseY);
            background(55);
            noStroke();
            fill(255);
            rect(300, 1, 0.1, 800);
            if(moveLeft) Player1.xPlayer -= speed;
            if(moveRight) Player1.xPlayer += speed;
            if(moveLeft1) Player2.xPlayer -= speed;
            if(moveRight1) Player2.xPlayer += speed;
            if (y0 &gt; height+15) //15 is the radius of the ball
            {
            y0 = -15; //Move it back to just above the screen
            x0 = random(width); //start in randmon spot
            y0_speed = random(3, 7); //Pick a new random speed
            }
            //Move the ball
            y0 += y0_speed; //Increase the balls y value
            //Ball
            fill(255, 255, 255);
            ellipse(x0, y0, 30, 30);
            Player1.display();
            Player2.display();
            }
            class Player {// Trying out classes xD
            color c;
            float xPlayer;
            float yPlayer;
            float WPlayer;
            float Hplayer;
            float pspeed;
            Player(color tempC, float xpos, float ypos, float padspeed) {
            c = tempC;
            xPlayer = xpos;
            yPlayer = ypos;
            Hplayer = 5;
            WPlayer = 40;
            pspeed = padspeed;
            }
            void display() {
            stroke(0);
            fill(c);
            rect(xPlayer, yPlayer, WPlayer,Hplayer);
            }
            }
            void keyPressed() {// player movement
            if (keyCode == LEFT) {
            moveLeft = true;
            } else if(keyCode == RIGHT) {
            moveRight = true;
            } else if(key == 'a') {
            moveLeft1 = true;
            } else if(key == 'd') {
            moveRight1 = true;
            }
            }

            void keyReleased() {//Player movement
            if (keyCode == LEFT) {
            moveLeft = false;
            } else if(keyCode == RIGHT) {
            moveRight = false;
            } else if(key == 'a') {
            moveLeft1 = false;
            } else if(key == 'd') {
            moveRight1 = false;
            }
            }
</code></pre>
]]></description>
   </item>
   <item>
      <title>Random Spikes in Real Time Data Graphing</title>
      <link>https://forum.processing.org/two/discussion/16416/random-spikes-in-real-time-data-graphing</link>
      <pubDate>Wed, 04 May 2016 01:25:14 +0000</pubDate>
      <dc:creator>agustinpfrpa</dc:creator>
      <guid isPermaLink="false">16416@/two/discussions</guid>
      <description><![CDATA[<p>Hi! So I am using this program to plot data from serial coming from an accelerometer connected to an Arduino. As you can see there are random spikes appearing in the plot. I know that it is not because of the data because I am looking at the data that is being transmitted and none of the points match with those in the image. Any suggestion as to what I can do to get rid of the random spikes? Thank you!</p>

<p>`import processing.serial.*;
PrintWriter writer;</p>

<p>Serial myPort;        // The serial port
int xPos = 0;         // horizontal position of the graph
float inByte = 0;
int lastxPos = 1;
int lastHeight = 0;</p>

<p>void setup () {
  // set the window size:
  size(800,600);</p>

<p>// List all the available serial ports
  // if using Processing 2.1 or later, use Serial.printArray()
  println(Serial.list());</p>

<p>// I know that the first port in the serial list on my mac
  // is always my  Arduino, so I open Serial.list()[0].
  // Open whatever port is the one you're using.
  myPort = new Serial(this, "COM3", 115200);</p>

<p>// don't generate a serialEvent() unless you get a newline character:
  myPort.bufferUntil('\n');</p>

<p>//writer = createWriter("new_data.txt");
  // set inital background:
  background(0);
}
void draw () {
  // draw the line:
  stroke(255,255,255);
    strokeWeight(1);
    //delay(5);
    line(lastxPos, lastHeight, xPos, height - inByte);
    lastxPos = xPos;
    lastHeight = int(height - inByte);
if (xPos &gt;= width) {
    xPos = 0;
    lastxPos = 0;
    background(0);
  } else {
    // increment the horizontal position:
    xPos++;
  }</p>

<p>}</p>

<p>void serialEvent (Serial myPort) {
  // get the ASCII string:
  if(myPort.available() &gt; 0){
  String inString = myPort.readStringUntil('\n');</p>

<p>if (inString != null) {
    // trim off any whitespace:</p>

<pre><code>inString = trim(inString);
// convert to an int and map to the screen height:
inByte = float(inString);
//println(inByte);    
inByte = constrain(inByte, 0, 32768);
println(inByte/16384.0);
inByte = map(inByte, 0, 32768, 0, height);
</code></pre>

<p>}</p>

<p>}
}`</p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/328/WHYD2YO367A4.png" alt="RandomLines" title="RandomLines" /></p>
]]></description>
   </item>
   <item>
      <title>Trying to make a Square like a potoshop</title>
      <link>https://forum.processing.org/two/discussion/15948/trying-to-make-a-square-like-a-potoshop</link>
      <pubDate>Sun, 10 Apr 2016 15:02:51 +0000</pubDate>
      <dc:creator>thefool</dc:creator>
      <guid isPermaLink="false">15948@/two/discussions</guid>
      <description><![CDATA[<p>hii I was a novice programmer.
i am from indonesia and I am very interested in the programming language processing.</p>

<p>I've watched several videos Daniel Shiffman
about how to create a class, function, rect, circle, etc.
but still not all that I have seen.</p>

<p>I am trying to create a function
which can create a box shape as in potoshop</p>

<p>This is the result of my work</p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/599/J1CBAPBLBAFF.JPG" alt="6" title="6" /></p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/690/ZK1MO0UE0LBM.JPG" alt="7" title="7" /></p>

<p>I may look fail :'(
but I hope you can teach me
how to write the code.</p>

<p>thx.... 
i am sorry if my english so bad</p>
]]></description>
   </item>
   <item>
      <title>Creating Forces from Image</title>
      <link>https://forum.processing.org/two/discussion/15775/creating-forces-from-image</link>
      <pubDate>Thu, 31 Mar 2016 04:18:45 +0000</pubDate>
      <dc:creator>json</dc:creator>
      <guid isPermaLink="false">15775@/two/discussions</guid>
      <description><![CDATA[<p>Hi all,</p>

<p>I'm new to the forum and fairly new to Processing. I've scoured around and founds lots of help so far, but now I'm at a point where I'm not totally sure where to head.</p>

<p>I'd like to load an image, analyze each pixel's RGB value, and based on those values move particles in a certain direction.</p>

<p>So... a little pseudo code to explain my thoughts.</p>

<pre><code>Load image, get it's pixels
Go through each pixel, separate it's RGB values
If R &lt; 128, velocity.x = -1
If R &gt; 128, velocity.x = 1
If G &lt; 128, velocity.y = -1
If G &gt; 128, velocity.y = 1
Ignore the B values, I don't really need them.

position.add(speed) to move the particle. 
</code></pre>

<p>Initially I was going using the get() function so each particle feeds it's position, looks at the color behind it, analyzes it, and moves accordingly, but that's waaaaay to slow for hundreds of particles.</p>

<p>I'm thinking of loading all of the pixel values into an array (does it need to be a 2D array, for x and y values?) at the start so it's all in memory, and then each particle reads where it's at on the screen, finds the corresponding image pixel index, and just pulls the vector out, without having to re-analyze the image on every frame since it's not changing.</p>

<p>I've been working with vectors for a bit, but I don't have much experience with arrays. Is this a good approach? Can anyone point me in the right direction?</p>
]]></description>
   </item>
   <item>
      <title>Noise walker – Weird direction tendency</title>
      <link>https://forum.processing.org/two/discussion/15492/noise-walker-weird-direction-tendency</link>
      <pubDate>Mon, 14 Mar 2016 19:17:50 +0000</pubDate>
      <dc:creator>injuvik</dc:creator>
      <guid isPermaLink="false">15492@/two/discussions</guid>
      <description><![CDATA[<p>Hi coders,</p>

<p>i've wrote a noise-walker-program, but i wonder why the direction of the walker is always top-left?! My intention was to write a program similar to Daniel Shiffmans random walker, but just with noise and a smooth, not so edgy motion... Here's the code:</p>

<pre><code>Dot dot;

void setup() {
  size(900, 900);
  background(#222222);
  noStroke();
  dot = new Dot();
  fill(#eeeeee);
}

void draw() {
  dot.move();
  dot.display();
}



class Dot {

  int x = width/2;
  int y = height/2;
  float xoff =100;
  float yoff = 200;
  int xspeed;
  int yspeed;


  void move() {

    float thenoise1 = noise(xoff);  
    float thenoise2 = noise(yoff);  
    int stepx = int(map(thenoise1, 0, 1, 0, 3))-1; 
    int stepy = int(map(thenoise2, 0, 1, 0, 3))-1; 

    x = x + stepx;
    y = y + stepy;
    xoff = xoff + 10;
    yoff = yoff + 10;

    x = constrain(x, 0, width);
    y = constrain(y, 0, height);
  }

  void display() {
    ellipse(x, y, 2, 2);
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Noise Walker Edge Detection</title>
      <link>https://forum.processing.org/two/discussion/15490/noise-walker-edge-detection</link>
      <pubDate>Mon, 14 Mar 2016 18:43:41 +0000</pubDate>
      <dc:creator>injuvik</dc:creator>
      <guid isPermaLink="false">15490@/two/discussions</guid>
      <description><![CDATA[<p>Hey guys,</p>

<p>i've created a little random walker-sketch, but i have no idea how to tell the dot to stay inside the canvas. Any suggestions? Thank you !!!</p>

<p>PS: I'm also happy about any kind of advices for better syntax. :-)</p>

<pre><code>Dot dot;

void setup() {
  size(100, 100);
  background(#222222);
  noStroke();
  dot = new Dot();
  fill(#eeeeee);
}

void draw() {
  dot.move();
  dot.display();
}



class Dot {

  int x = width/2;
  int y = height/2;
  float xoff =100;
  float yoff = 200;
  int xspeed;
  int yspeed;


  void move() {

    float thenoise1 = noise(xoff);  
    float thenoise2 = noise(yoff);  
    int stepx = int(map(thenoise1, 0, 1, 0, 3))-1; 
    int stepy = int(map(thenoise2, 0, 1, 0, 3))-1; 

    x = x + stepx;
    y = y + stepy;
    xoff = xoff + 0.1;
    yoff = yoff + 0.1;
  }

  void display() {
    ellipse(x, y, 2, 2);
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Why isn't my object moving anymore?</title>
      <link>https://forum.processing.org/two/discussion/14792/why-isn-t-my-object-moving-anymore</link>
      <pubDate>Sat, 06 Feb 2016 21:08:57 +0000</pubDate>
      <dc:creator>Jonasan</dc:creator>
      <guid isPermaLink="false">14792@/two/discussions</guid>
      <description><![CDATA[<p>I'm making some kind of moving and turning stars. I started with one object and now made an array of objects from it. Somehow, while my single object was turning, the 20 objects don't do that anymore.
I have a function called "move" which adds one to the rotation. That DID work (look here: <a href="http://www.openprocessing.org/sketch/305960/" target="_blank" rel="nofollow">http://www.openprocessing.org/sketch/305960/</a>)</p>

<pre><code>float r = 40, hoek=0, radhoek; 
int arm=4;
float[] xpos = new float[20];
float[] ypos = new float[20];
TurningWheel[] turningwheel = new TurningWheel[20];

void setup() {
  size(800, 800);
  for (int count=0; count &lt;20; count=count+1) {
    turningwheel[count] = new TurningWheel(random(60, 800), random(60, 800));
  }
}

void draw() {
  background(210);
  for (int count=0; count &lt;20; count=count+1) {
    turningwheel[count].display();
    turningwheel[count].move();
    turningwheel[count].numberArms();
  }
}

class TurningWheel {
  float xpos, ypos;

  TurningWheel (float tempxpos, float tempypos) {
    radhoek=radians(hoek);
    xpos = tempxpos;
    ypos = tempypos;
  }

  void display() {
    for (int i = 0; i &lt; arm; i++) {
      float[] xarmen = new float[arm];
      float[] yarmen = new float[arm];  
      xarmen[i] = xpos + r * cos(radhoek+radians(i*360/arm));
      yarmen[i] = ypos + r * sin(radhoek+radians(i*360/arm));
      line(xpos, ypos, xarmen[i], yarmen[i]);
      ellipse(xarmen[i], yarmen[i], 6, 6);
    }
    ellipse(xpos, ypos, 20, 20);
  }

  void move() {
    if (hoek&gt;360) {
      hoek=1;
    }
    hoek+=1;
  }

  void numberArms() {  
    if (keyPressed) {
      if (key == 'a') {
        arm=arm+1;
      }
    } else if (key == 'q') {
      arm=arm-1;
    }
    if (arm &lt; 1) {
      arm = 1;
    }
    if (arm &gt; 18) {
      arm = 18;
    }
  }
}
</code></pre>

<p>Another problem is, you can choose the number of arms of one "star", by pressing a and q. With the single star, it worked, though in stead of adding (or subtracting) one arm for each time you pressed a or q, it added (subtracted) more. Now, it just goes from the minimum (1) to the maximum (18). Why isn't it going stepwise?</p>
]]></description>
   </item>
   <item>
      <title>Collision Between Ball and Paddle for Pong type game</title>
      <link>https://forum.processing.org/two/discussion/14527/collision-between-ball-and-paddle-for-pong-type-game</link>
      <pubDate>Tue, 19 Jan 2016 06:17:57 +0000</pubDate>
      <dc:creator>TAProcessor</dc:creator>
      <guid isPermaLink="false">14527@/two/discussions</guid>
      <description><![CDATA[<p>Hello,</p>

<p>I am relatively new to processing, having only started learning it this year as part of my course at university. I am writing a small game for part of my project but am having trouble working out how to get collision between to class-objects. I need to detect when the ball has hit the paddle. I can do the points and reversing of direction myself, but I really am struggling with the collision.</p>

<p>Here is my code:
Void setup and draw functions</p>

<pre><code>int P1points = 0;
int P2points = 0;

Ball myBall;
P1Paddle myPaddle;
P2Paddle yourPaddle;

void setup() {
  size(1280, 720);
  background(0);

  myBall = new Ball(320, 500);
  myPaddle = new P1Paddle(1260,308);
  yourPaddle = new P2Paddle(20,308);
}
void draw() {
  background(0);
  smooth();
  textSize(32);
  text("P1 Points: " + P1points, 10, 40);
  text("P2 Points: " + P2points, 10, 80);
  stroke(255);
  line(0, 90, 1280, 90);
  line(0, 95, 1280, 95);
  line(0, 710, 1280, 710);
  line(0, 715, 1280, 715);
  myBall.display();
  myPaddle.display();
  if (key == ENTER) {
    myBall.run();
  }
  myPaddle.run();
  yourPaddle.run();

}

  class P1Paddle {
  //GLOBAL VARIABLES
  float x = 0;
  float y = 0;
  float xspeed = 3;
  float yspeed = 3;
  int pad2w = 10;
  int pad2h = 80;

  //CONSTRUCTOR
  P1Paddle(float _x, float _y) {
    x = _x;
    y = _y;
  }
  //FUNCTIONS
  void run() {
    display();
    move();
  }
  void move() {
    if (key == CODED) {
      if (keyCode == UP) {
        if (keyPressed) {
          y = y - 4;
        }
        if (y &lt;=145) {
          y = 145;
        }
      }
      if (keyCode == DOWN) {
        if (keyPressed) {
          y = y + 4;
        }
        if (y &gt;= 660) {
          y = 660;
        }
      }
    }
  }

  void display() {
    rectMode(CENTER);
    rect(x, y, pad2w, pad2h);
  }
}

  class P2Paddle {
  //GLOBAL VARIABLES
  float x = 0;
  float y;
  float xspeed = 3;
  float yspeed = 3;
  int padw = 10;
  int padh = 80;

  //CONSTRUCTOR
  P2Paddle(float _x, float _y) {
    x = _x;
    y = _y;
  }
  //FUNCTIONS
  void run() {
    display();
    move();
  }
  void move() {
    if (keyPressed) {
      if (key == 'W' || key == 'w') {
        y = y - 4;
      }
      if (y &lt;=145) {
        y = 145;
      }
      if (key == 'S' || key == 's') {
        y = y + 4;
      }
      if (y &gt;= 660) {
        y = 660;
      }
    }
  }

  void display() {
    rectMode(CENTER);
    rect(x, y, padw, padh);
  }
}


  class Ball {
  //GLOBAL VARIABLES
  float x = 0;
  float y = 0;
  float xspeed = 3;
  float yspeed = 3;
  int ew = 15;
  int eh = 15;

  //CONSTRUCTOR
  Ball(float _x, float _y) {
    x = _x;
    y = _y;
  }
  //FUNCTIONS
  void run() {
    display();
    move();
    bounceY();
    addpoints();
  }
  void move() {
    x += xspeed;
    y += yspeed;
  }
  void display() {
    ellipse(x, y, ew, eh);
  }
  void bounceY() {
    if (y &lt;= 95) {
      yspeed = yspeed * -1;
    }
    if (y &gt;= 710) {
      yspeed = yspeed * -1;
    }
  }
  void addpoints() {
    if (x &gt;= 1250) {
      P1points = P1points +1;
    }
    if (x &lt;= 18) {
      P2points = P2points +1;
    }
  }
}
</code></pre>

<p>Any help would be greatly appreciated..Oh and the other problem I have to is that when I press enter the ball will move, but trying to move the paddles at the same time results in the ball pausing...Though I am trying to work all this out.</p>
]]></description>
   </item>
   <item>
      <title>Displaying text makes my frameRate fall</title>
      <link>https://forum.processing.org/two/discussion/13069/displaying-text-makes-my-framerate-fall</link>
      <pubDate>Sat, 17 Oct 2015 16:16:27 +0000</pubDate>
      <dc:creator>jimrolland</dc:creator>
      <guid isPermaLink="false">13069@/two/discussions</guid>
      <description><![CDATA[<p>Hello,
I have a little problem. On a processing project for android, I have to display a lot of text on the screen.
I use :</p>

<pre><code>string myString = "lots of words";
textFont(myFont, 20);
text(myString, x, y);
</code></pre>

<p>but the performances are very low (5 fps).
Does anyone has an advice for a best performance?</p>

<p>Thanks a lot,
JM</p>
]]></description>
   </item>
   <item>
      <title>Image Processing</title>
      <link>https://forum.processing.org/two/discussion/9038/image-processing</link>
      <pubDate>Wed, 14 Jan 2015 12:48:10 +0000</pubDate>
      <dc:creator>Domino60</dc:creator>
      <guid isPermaLink="false">9038@/two/discussions</guid>
      <description><![CDATA[<p>Hi, I just started to learn Processing because I need to do some stuffs. I went thru some tutorials about "Images and Pixels"
but there is only some basic code how to load and process image and pixels.
My question is, there is an example where I can find how to process a image with an exact formula ? 
what i mean is to load a image, process the image thru a formula and have a output of the loaded image but changed (in a 2nd window "right to the 1st image") with the processed image (formula).</p>
]]></description>
   </item>
   <item>
      <title>How do you constrain an angle</title>
      <link>https://forum.processing.org/two/discussion/12887/how-do-you-constrain-an-angle</link>
      <pubDate>Thu, 08 Oct 2015 02:00:35 +0000</pubDate>
      <dc:creator>gperez</dc:creator>
      <guid isPermaLink="false">12887@/two/discussions</guid>
      <description><![CDATA[<p>Hi. I'm trying to constrain an angle. , measured in radians. But radians takes negative values so constrain() method will not work.</p>

<p>So, i tried converting radians to angles, constrain degrees and convert to radians again. But the result is the same.</p>

<p><code>a = radians(constrain(degrees(a), 90, 270));</code></p>

<p>Any clue?</p>
]]></description>
   </item>
   <item>
      <title>How do you use mouse wheel to change a variable</title>
      <link>https://forum.processing.org/two/discussion/12066/how-do-you-use-mouse-wheel-to-change-a-variable</link>
      <pubDate>Thu, 13 Aug 2015 14:01:36 +0000</pubDate>
      <dc:creator>Gromek999</dc:creator>
      <guid isPermaLink="false">12066@/two/discussions</guid>
      <description><![CDATA[<p>I want to create a sizeable paint brush in a paint program I am making, and I want the mousewheel to change the variable I have for the size of the brush I use. How do I go about doing this? :) I am new to programming</p>
]]></description>
   </item>
   <item>
      <title>out of Boundry Error</title>
      <link>https://forum.processing.org/two/discussion/11908/out-of-boundry-error</link>
      <pubDate>Thu, 30 Jul 2015 21:03:26 +0000</pubDate>
      <dc:creator>aryhawezy</dc:creator>
      <guid isPermaLink="false">11908@/two/discussions</guid>
      <description><![CDATA[<p><strong>can anyone tell me pls where is my error ? i think in line 268 **
**really appreciated</strong></p>

<pre><code>int[][][] space = new int[40][40][20];
boolean move_ok = true;
int time;
void setup() {
  size(1000, 1000, P3D);
  for (int i = 0; i &lt; 200; i++) { // number of balls
    space[int(random(40))][int(random(40))][0] = 1;
  }
  space[25][20][0] = 2;// initial food on the ground

  // 4 existing buildings 
  for (int x = 10; x &lt; 15; x++) {
    for (int y = 20; y &lt; 25; y++) {
      for (int z = 0; z &lt; 11; z++) {
        space[x][y][z] = 4;
      }
    }
  }
  for (int x = 35; x &lt; 40; x++) {
    for (int y = 20; y &lt; 25; y++) {
      for (int z = 0; z &lt; 11; z++) {
        space[x][y][z] = 4;
      }
    }
  }
  for (int x = 20; x &lt; 30; x++) {
    for (int y = 5; y &lt; 8; y++) {
      for (int z = 0; z &lt; 6; z++) {
        space[x][y][z] = 4;
      }
    }
  }
  for (int x = 20; x &lt; 30; x++) {
    for (int y = 35; y &lt; 38; y++) {
      for (int z = 0; z &lt; 6; z++) {
        space[x][y][z] = 4;
      }
    }
  }
  for (int x = 20; x &lt; 30; x++) {
    for (int y = 35; y &lt; 38; y++) {
      for (int z = 6; z &lt; 7; z++) {
        space[x][y][z] = 0;
      }
    }
  }
  // end of buildings

  time = -1;
}
//.............................................................

void draw() {

  if (millis() &gt; time ) {// control the speed by millisecond
    move();
    time = millis() +100;
  }
  background(255);
  translate(width/2, height/2);

  pushMatrix();// camera setup
  scale(330);
  lights();
  popMatrix();
  rotateY(map(mouseX, 0, width, -PI, PI));
  rotateX(-map(mouseY, 0, height, -PI, PI));
  translate(-250, -250, -250);
  fill(#4F504F);
  pushMatrix();
  translate(450, 450, -15);
  box(1000, 1000, -10);
  popMatrix(); //end of camera setup


  //.......................................................
  // moving on grid

  for (int k = 0; k&lt;20; k++) {
    for (int j = 0; j&lt;40; j++) {
      for (int i = 0; i&lt;40; i++) {
        pushMatrix();
        translate(20*i, 20*j, 20*k);
        switch(space[i][j][k]) { // switch between the grids 
        case 0:
          break;
        case 1: // ant
          fill(#25F018);
          noStroke();
          sphere(5);
          break;

        case 2: // food
          fill(#FF3E41);
          noStroke();
          box(20);
          break;

        case 3: // empty food
          pushMatrix();
          translate(-9, -9, -9);
          noStroke();
          fill(100);
          for (int m=0; m&lt;10; m++) {
            pushMatrix();
            translate(2*m, 0, 0);
            box(2, 2, 2);
            popMatrix();

            pushMatrix();
            translate(0, 2*m, 0);
            box(2, 2, 2);
            popMatrix();

            pushMatrix();
            translate(0, 0, 2*m);
            box(2, 2, 2);
            popMatrix();
          }

          for (int n=-9; n&lt;0; n++) {
            pushMatrix();
            translate(18, 0, -2*n);
            box(2, 2, 2);
            popMatrix();

            pushMatrix();
            translate(18, -2*n, 0);
            box(2, 2, 2);
            popMatrix();

            pushMatrix();
            translate(-2*n, 18, 0);
            box(2, 2, 2);
            popMatrix();
          }

          for (int p=-9; p&lt;0; p++) {
            pushMatrix();
            translate(0, 18, -2*p);
            box(2, 2, 2);
            popMatrix();

            pushMatrix();
            translate(18, -2*p, 18);
            box(2, 2, 2);
            popMatrix();

            pushMatrix();
            translate(-2*p, 18, 18);
            box(2, 2, 2);
            popMatrix();
          }
          for (int r=-9; r&lt;0; r++) {
            pushMatrix();
            translate(0, -2*r, 18);
            box(2, 2, 2);
            popMatrix();

            pushMatrix();
            translate(-2*r, 0, 18);
            box(2, 2, 2);
            popMatrix();

            pushMatrix();
            translate(18, 18, -2*r);
            box(2, 2, 2);
            popMatrix();
          }
          popMatrix();
          break;

        case 4: // building
          pushMatrix();         
          noFill();
          stroke(0);
          strokeWeight(1);
          box(20);
          popMatrix();
          break;

        case 5: // test
          pushMatrix();         
          fill(#4CB91E);
          box(20);
          popMatrix();
          break;
        }
        popMatrix();
      }
    }
  }
}
//.................................................

void move() {

  if ( !move_ok ) { 
    return;
  }
  //................................................


  int[][][] next = new int[40][40][20];
  for (int k = 0; k&lt;20; k++) {
    for (int j = 0; j&lt;40; j++) {
      for (int i = 0; i&lt;40; i++) {
        switch(space[i][j][k]) {
        case 0:
          break;
        case 1: // ant behavior
          boolean be_food = false;
          int food_count = 0;
          int count=0;
          // reading (-1,0,1)of each grid it means one before and
          // one after to finding out if there is any sharing face  
          // with the food and changing to food if it is.
          for (int a = -1; a &lt; 2; a++) {

              if (space[i+a][j][k] == 2) {
                be_food = true;
                next[i][j][k] = 2;
                food_count++;
            }

              if (space[i][j+a][k] == 2) {
                be_food = true;
                next[i][j][k] = 2;
                food_count++;
            }


              if (space[i][j][k+a] == 2) {
                be_food = true;
                next[i][j][k] = 2;
                food_count++;
            }
          }
          //...........................................................      


          // restricting the area around the food by 5 pixes in x,y only

          if ((next[i][j][k] == next[30][j][k])) {
            next[i][j][k] = 0;
          } 
          if ((next[i][j][k] == next[20][j][k])) {
            next[i][j][k] = 0;
          }
          if ((next[i][j][k] == next[i][15][k])) {
            next[i][j][k] = 0;
          }
          if ((next[i][j][k] == next[i][25][k])) {
            next[i][j][k] = 0;
          }
          // end of restriction
          //..........................................................................................

          if (( food_count &gt;= 2) ) { // if the sharing face is more than 2 the food become empty 
            next[i][j][k] = 3;
          } 
          // this condition makes the movement of the agents 
          boolean done = false;  
          while (!done &amp;&amp; !be_food  ) { // used the while loop cuz it never stops until the condition is true
            int a = int(random(-2, 2));
            int b = int(random(-2, 2));
            int c = int(random(-2, 2));
            if (next[i+a][j+b][k+c] &gt;= space[i][j][k]) {
            next[i+a][j+b][k] = space[i][j][k];
            done = true;
            }
          }
          break;
        case 2:
          next[i][j][k] = 2;
          break;
        case 3:
          next[i][j][k] = 3;
          break;
        case 4:
          next[i][j][k] = 4;
          break;
        case 5:
          next[i][j][k] = 5;
          break;
        }
      }
    }
  }
  move_ok = false; // when not moving
  for (int k = 0; k&lt;20; k++) {
    for (int j = 0; j&lt;40; j++) {
      for (int i = 0; i&lt;40; i++) {
        space[i][j][k] = next[i][j][k];
        move_ok = true;
      }
    }
  }
}  // end of move void        
//......................................................
</code></pre>
]]></description>
   </item>
   <item>
      <title>How to move a circle back and forth using mousePressed()</title>
      <link>https://forum.processing.org/two/discussion/11891/how-to-move-a-circle-back-and-forth-using-mousepressed</link>
      <pubDate>Wed, 29 Jul 2015 23:13:17 +0000</pubDate>
      <dc:creator>Altharis</dc:creator>
      <guid isPermaLink="false">11891@/two/discussions</guid>
      <description><![CDATA[<p>Hi :)
I'm trying to make an ellipse move horizontally when I press on it, then make it move back to its original position if pressed again. Right now, I only know how to make it move further to the right every time I press. Sorry, I couldn't find it in any beginner guides or videos.</p>

<p>Right now, it checks if the mouse was pressed on the circle, then it does the background(255) to get rid of previous circles and it draws a new circle.  If I press outside of the circle, the circle stays where it is.</p>

<pre><code>int circleX = 100;
int circleY = 100;

void setup() {
  size(200,200);
  background(255);
}

void draw() {
  ellipseMode(CENTER);
  stroke(0);
  fill(175);
  ellipse(circleX,circleY,50,50);
}

void mousePressed() {
  if (dist(mouseX, mouseY,circleX,circleY)&lt;=25) {
      background(255);
     circleX = circleX + 50;
   }
 else {
    circleX = circleX;
 } 
}
</code></pre>
]]></description>
   </item>
   </channel>
</rss>