Hello!
I put in some Code.
First you have x= something to make it move left and right (with directionX giving the direction).
Then you have y= something to make it move up or down (with directionY).
When you type arrow Right, you want to have directionX = +1 (with directionY = 0, so no up or down movement).
Therefore, in keyPressed you find for RIGHT:
- directionX=1;
- directionY=0;
For the other directions it is the same: Define the direction you want to go to and switch the other direction to 0.
There are more elegant ways doing that, but enough for now.
Greetings, Chrisir
The whole Code:
- int radius = 10, directionX = 1, directionY = 0;
- float x=20, y=20, speed=0.5;
- // =========================================================
- void setup()
- {
- size(500, 500);
- smooth();
- // fill (color(222, 22, 22));
- noStroke();
- ellipseMode(RADIUS);
- }
- void draw()
- {
- background(0);
- // changing Position
- x=x+speed*directionX;
- y=y+speed*directionY;
- // check boundaries
- if ((x>width-radius) || (x<radius))
- {
- directionX=-directionX;
- }
- if ((y>height-radius) || (y<radius))
- {
- directionY=-directionY;
- }
- // draw
- // if(direction==1)
- // rect(x, y, 20, 20);
- fill (color(222, 22, 22));
- ellipse (x, y, radius, radius); // body
- fill (color(22, 82, 22));
- ellipse (x-4, y-4, 2, 2); // the eye
- }
- // =========================================================
- void keyPressed()
- {
- if (key == CODED)
- {
- if (keyCode == LEFT)
- {
- //if (directionX>0) {
- directionX=-1;
- directionY=0;
- //}
- }
- else if (keyCode == RIGHT)
- {
- //if (directionX<0) {
- directionX=1;
- directionY=0;
- //}
- }
- else if (keyCode == UP)
- {
- //if (directionY<0) {
- directionY=-1;
- directionX=0;
- //}
- }
- else if (keyCode == DOWN)
- {
- //if (directionY<0) {
- directionY=1;
- directionX=0;
- //}
- }
- }
- }
- // =========================================================