We are about to switch to a new forum software. Until then we have removed the registration on this forum.
creating a football game, need to create a mechanic where the player will move diagonally when two certain keys are pressed in combination. Here's my code so far;
thanks in advance
class Blue {
PVector pos;
float radius;
color Colour = color (0, 0, 255);
Blue (float x, float y, float r_, int red, int green, int blue) {
pos = new PVector(x, y);
radius = r_;
Colour = color (red, green, blue);
}
void displayBlue () {
fill (Colour);
strokeWeight (2);
stroke(255);
ellipse(pos.x, pos.y, radius, radius);
}
void ballCollision () {
}
void moveBlue () {
if ((keyPressed == true) && (key == 'a')) {
pos.x = pos.x -3;
}
if ((keyPressed == true) && (key == 'd')) {
pos.x = pos.x +3;
}
if ((keyPressed == true) && (key == 'w')) {
pos.y = pos.y -3;
}
if ((keyPressed == true) && (key == 's')) {
pos.y = pos.y +3;
}
}
}
Answers
Use a set of boolean variables to track whether particular keys are being pressed. Something like:
Then in the
keyPressed()
function, set them totrue
, and in thekeyReleased()
function, set them tofalse
. Finally, just check the values of the variables in thedraw()
function.Shameless self-promotion: I wrote a tutorial on user input in Processing, including this technique, available here.
Hi thanks for the reply, I followed the tutorial on the link you gave, it didn’t work for me, I was wondering if it was to do with the fact that I’m using this within a class? Could you explain how to use keyPressed and KeyReleased within a class?
The
keyPressed()
andkeyReleased()
functions need to be inside the top-level sketch, not inside a class.Thanks again, i've tried that it's still not moving, i'll post my code below, maybe you'll be able to spot an obvious mistake;
Sorryyyyyyy i figured it out :P, i needed to rename the booleans in both the keyPressed & keyReleased functions to 'blue.'
thanks so much for the help
Note that you only need one set of these variables, since they're global for your whole sketch. You don't need another copy of them inside your class.
http://Studio.ProcessingTogether.com/sp/pad/export/ro.91tcpPtI9LrXp