I have been coding a simple game and I’m stuck in the key pressed events and my intention is to make my character move backwards, onwards, upwards and downwards. Where should I place the keypressed code to connect it with the character? And the jumping part of my code should be inside the key pressed code? Please, excuse my lack of knowledge towards Processing once I have been studying it for just a few weeks. My code:
//****** Setup section starts here ****** //
// images
PImage background;
// bee character
float charSpeed = 5.5;
float charX, charY;
PImage[] charImage= new PImage[4];
int px, pf;
public void setup() {
size(800, 600);
noFill(); // to adjust the image in the screen properly in fullscreen
background = loadImage("YellowFlowers.jpg");
background.resize(width, height);
// load bee
charImage[0] = loadImage("bee walk 1.png");
charImage[1] = loadImage("bee walk 2.png");
charImage[2] = loadImage("bee walk 3.png");
charImage[3] = loadImage("bee walk 4.png");
}
// ******* drawing section ! *********** //
// background draw
public void draw() {
image(background, 0, 0);
//bee character
image(charImage[pf], px, 0);
if (++pf > 3) pf = 0;
}
Easiest way to capture key presses (in my opinion) is to use keyPressed() function. It’s called each time a key is pressed. In that function check what key is pressed and save something to a variable, direction for instance. It can be text “up”, “down” etc. Then in draw() cycle check if movement direction is set, act accordingly and as last thing set remember to empty your direction variable (direction="") so there needs to be a new key press until it has a directional value again.
Hi! I have already coded the key pressed part and I can move my character the way I wanted with the keyboard. But I still need guidance when it comes to where I should place the jumping code. Should I place it in the key pressed function as well?
if(keyPressed) {... in draw() (registers throughout) and
The function keyPressed() (registers only once)
You can distinguish the two in the reference by the brackets (): the function has them, the variable has not.
For moving the guy left and right, I think if(keyPressed) {... in draw() would be the way to go, because in most games when you release the key, the player stops.