So I’m writing a Super Mario/platform game for school, and I’m trying to make a hand-drawn character move around the screen, in three modes:
- Idle: just standing, default mode if no key is pressed
- Running: when right or left key is pressed
- Jumping: when up key is pressed
Idle and jumping is done with absolutely no problems, but I got stuck on the running part. I drew four images for the running character, but it doesn’t work outside of void draw ()
.
So it works fine like this:
PImage idle;
PImage [] run = new PImage [4];
int currentImageNum;
int NumofImages = 4;
PImage jump;
int x;
int y;
void setup ()
{
size (1280, 720);
smooth ();
//standing
idle = loadImage ("idle.png");
//running
run [0] = loadImage ("run0.png");
run [1] = loadImage ("run1.png");
run [2] = loadImage ("run2.png");
run [3] = loadImage ("run3.png");
currentImageNum = 0;
frameRate (12);
//jumping
jump = loadImage ("jump.png");
x = width/2;
y = height/2;
}
void draw ()
{
background (0);
image (run [currentImageNum], x, y, 100, 100);
currentImageNum++;
if (currentImageNum >= NumofImages)
currentImageNum = 0;
}
So that works fine. But that’s just the character running and nothing else. So when I try something like this (putting the array inside void run ()
so I can just reference the function when I need it):
PImage idle;
PImage [] run = new PImage [4];
int currentImageNum;
int NumofImages = 4;
PImage jump;
int x;
int y;
PImage boy;
boolean load = false;
void setup () {
size (1280, 720);
smooth ();
//standing
idle = loadImage ("idle.png");
//running
run [0] = loadImage ("run0.png");
run [1] = loadImage ("run1.png");
run [2] = loadImage ("run2.png");
run [3] = loadImage ("run3.png");
currentImageNum = 0;
frameRate (12);
//jumping
jump = loadImage ("jump.png");
x = width/2;
y = height/2;
image (idle, x, y, 100, 100);
}
void draw () {
background (0);
if (load)
image (boy, x, y, 100, 100);
}
//keyboard movements
void keyPressed() {
if (key == CODED) {
if (keyCode == LEFT) {
run ();
load = true;
} else if(keyCode == RIGHT) {
run ();
load = true;
} else if(keyCode == UP) {
boy = loadImage ("jump.png");
load = true;
}
}
}
void keyReleased() {
if (key == CODED) {
if (keyCode == LEFT) {
boy = loadImage ("idle.png");
load = false;
} else if(keyCode == RIGHT) {
boy = loadImage ("idle.png");
load = false;
} else if(keyCode == UP) {
boy = loadImage ("idle.png");
load = false;
}
}
}
void run () {
image (run [currentImageNum], x, y, 100, 100);
currentImageNum++;
if (currentImageNum >= NumofImages)
currentImageNum = 0;
}
It says Null Pointer Exception. I have also tried replacing what’s inside the void run () with a for loop, but then it simply won’t run.
The for loop in question:
for (int i = 0; i < run.length; i++) {
run[i] = loadImage("run"+i+".png");
}
I’m really at loss at where I went wrong. Any help or pointers is very, very appreciated. Thank you in advance!