Hi there,
I am very new to processing, only been playing around with it for a few weeks but I am trying to make a very simple snake like interaction, whereby the user can press 4 keys to move an image in a direction and it leave a trail of the said images behind it. Here is my code at present:
Code:Snake[] mySnake = new Snake[50];
PImage b;
void setup() {
size(400,400);
smooth();
b = loadImage("2.png");
for (int i = 0; i < mySnake.length; i++) {
mySnake[i] = new Snake(width/2, width/2, 1);
}
}
void draw() {
background(255);
for (int i = 0; i < mySnake.length-1; i++) {
mySnake[i] = mySnake[i+1];
mySnake[i].display();
if(keyPressed) {
if (key == 's' || key == 'S') {
mySnake[i].moveleft();
} else if (key == 'a' || key == 'A') {
mySnake[i].moveright();
} else if (key == 'z' || key == 'Z') {
mySnake[i].movedown();
} else if (key == 'w' || key == 'W') {
mySnake[i].moveup();
}
}}
}
//Snake variables
class Snake {
float xpos, ypos, xspeed;
Snake(float tempxpos, float tempypos, float tempxspeed) {
xpos = tempxpos;
ypos = tempypos;
xspeed = tempxspeed;
}
//Then add a function to it to draw the snake
void display() {
image(b, xpos, ypos);
}
void moveleft() {
xpos = xpos + xspeed;
xpos = constrain(xpos, 0, width);
}
void moveright() {
xpos = xpos - xspeed;
xpos = constrain(xpos, 0, width);
}
void moveup() {
ypos = ypos - xspeed;
ypos = constrain(ypos, 0, height);
}
void movedown() {
ypos = ypos + xspeed;
ypos = constrain(ypos, 0, height);
}
}
I'm pretty sure this isn't the right way of thinking but I'm a bit stuck. Atm it just had a very weird sonic like effect and moves too fast, I think this is due to this:
for (int i = 0; i < mySnake.length-1; i++) {
mySnake[i] = mySnake[i+1];
The reason I used an array was because I thought I'd need one to duplicate the snake object each time and have it duplicate behind it but I'm just not quite sure how to make it do this...
Any help is appreciated at all as I'm very newto all of this but really want to get to grips it.
Thankyou!