We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › How to achieve smooth x / y movment
Page Index Toggle Pages: 1
How to achieve smooth x / y movment? (Read 1223 times)
How to achieve smooth x / y movment?
Nov 29th, 2009, 5:10pm
 
I have an ellipse that should move left or right based on the arrow keys. The way I have it set up right now is that when you press an arrow key the ellipse's x position is increased by 10 or decremented by 10. However, this makes the ellipse 'jerk' across the screen 10px at a time which is less than ideal. Is there a way to implement smoother movement?

Example code:

int xpos = 150;
int ypos = 150;

void setup(){
 size(300, 300);
 fill(128);
}

void draw(){
background(255);
ellipse(xpos, ypos, 50, 50);
}

void keyPressed() {
 if (key == CODED) {
   if (keyCode == LEFT) {
     xpos -= 10;
   } else if (keyCode == RIGHT) {
     xpos += 10;
   }
 }
}
Re: How to achieve smooth x / y movment?
Reply #1 - Nov 29th, 2009, 5:41pm
 
put it in draw



int xpos = 150;
int ypos = 150;

void setup(){
size(300, 300);
fill(128);
}

void draw(){
background(255);
ellipse(xpos, ypos, 50, 50);
if(keyPressed){
if (key == CODED) {
  if (keyCode == LEFT) {
    xpos -= 10;
  } else if (keyCode == RIGHT) {
    xpos += 10;
  }
}
}
}
Re: How to achieve smooth x / y movment?
Reply #2 - Nov 29th, 2009, 6:18pm
 
Far out.

Thanks again Cedric.

T
Re: How to achieve smooth x / y movment?
Reply #3 - Nov 30th, 2009, 1:19am
 
If you want to register multiple key presses at the same time it's worth doing some extra work and using booleans to store the key states:

Code:
int xpos = 150;
int ypos = 150;

boolean left;
boolean right;

void setup(){
 size(300, 300);
 fill(128);
}

void draw(){
 background(255);
 ellipse(xpos, ypos, 50, 50);
 
 if (left) {
   xpos -= 1;
 }
 if (right) {
   xpos += 1;
 }
}

void keyPressed() {
if (key == CODED) {
  if (keyCode == LEFT) {
    left = true;
  }
  if (keyCode == RIGHT) {
    right = true;
  }
}
}

void keyReleased() {
if (key == CODED) {
  if (keyCode == LEFT) {
    left = false;
  }
  if (keyCode == RIGHT) {
    right = false;
  }
}
}


Note also the removal of the 'else if'.  Obviously it's not entirely logical to be able to go left and right at the same time (try it and then see how it behaves with previous examples), but using the 'else if' gives one direction priority over the other: not always a good thing...
Page Index Toggle Pages: 1