rect(x position, y position, width, height)
But what we have not pointed out is what the x,y position is referencing to. For a ellipse the default is to the middle/center of the ellipse, but for a rectangle it is the upper left corner. One can change this reference for these types of objects with a command:
rectMode(CENTER);This will now make the x,y reference the center of the rectangle. It makes it a little easier to deal with the position of the obejects, I think.
to detect key presses, we can use some built in variables in the draw() routing. They are
- keyPressed - set to 1 (TRUE) when any key is pressed
- keyCode - Set to special keys that is not a sign, like arrow left (LEFT)
- key - Set to the key pressed, like 'A' or 'a' (note upper/lower case is not same)
// Run once at start
void setup() { // 500 pixels wide, 400 pixel height // This call will set system variables (width, height) size(500, 400); rectMode(CENTER); } // Variables to keep track of paddle int x_paddle = 250, y_paddle = 370; int paddle_width_half = 40; // Called every re-draw, defaul 30 times per second void draw() { // Check if keys are pressed if (keyPressed) { if (keyCode == RIGHT || key == 'd') { // Move paddle right x_paddle = x_paddle + 8; } else if (keyCode == LEFT || key == 'a') { // Move paddle left x_paddle = x_paddle - 8; } } // Clear screen to black background(0); // Set fill color to white fill(255); // draw paddle rect(x_paddle, y_paddle, paddle_width_half*2+1, 11); }Enter it, or copy paste, and run:
Try moving it with the left/right arrow. Personally I think we need to add so that one cannot go outside the screen. Adding this after the checking of keys will do that.
if (x_paddle>width) x_paddle = width; if (x_paddle<0) x_paddle = 0;
No comments:
Post a Comment