We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I have a randomly generating background, and I have been trying to add a playable character. The problem is that it will move, and the position will update, but a copy of the object stays where it originally was. When I try to redraw the background, everything except the character is removed. I cannot redraw the landscape at all.
Thanks, Esszach
int x = 0;
int index;
float[] worldSeed = new float[61];
int numBlocks;
int worldWidth = 0;
int worldHeight = 500;
int charY;
int charX;
void setup()
{
seedMaker();
size(1200,520);
background(255);
}
void draw()
{
drawWorld();
fill(55,155,255);
rect( charX, charY, 20, 40);//character
}
void seedMaker() //this creates the size for each block on the screen
{
for (int i=0; i < 60; i++)
{
worldSeed[i] = int(random(1,9));
}
index = int(random(0,30));
numBlocks = index;
}
void keyPressed()
{
if(key == 'a' || key == 'A')
{
charX = charX - 20;
}
if(key == 'd' || key == 'D')
{
charX = charX + 20;
}
}
void drawWorld() //this draws the landscape
{
for(int MFLB = 0; MFLB < 60; MFLB++)
{
if(MFLB == 0) {charY = int(500 - (worldSeed[0] * 20));}
worldHeight = 500;
if(worldSeed[MFLB] > 1)
{
for(int iNit = 1; iNit != worldSeed[MFLB]; iNit++)
{
rect(worldWidth,worldHeight,20,20);
worldHeight = worldHeight - 20;
}
worldWidth = worldWidth + 20;
}
else if(worldSeed[MFLB] == 1)
{
rect(worldWidth,worldHeight,20,20);
worldWidth = worldWidth + 20;
}
}
}
Answers
You forgot to reset
worldWidth
(a misleading name). So after first call you are drawing off screen. AddworldWidth = 0;
after line51
to fix this issue. There are some others things I can spot. This way you are only cleaning 'inside' the 'world' so when the character goes outside 'the world' it will remain. You create charY every time you call drawWorld(). Also, if the world will not change, perhaps would be better to draw it once into a PGraphics, convert it to a PImage, and use this every frame with background(image). or something like thisMaybe something like this? Let me know if you have any questions. What I am doing is using your seedMaker() function to declare how "tall" a stack of blocks is. When the character moves left or right he is positioned on top of the current stack of blocks.
Much obliged friend, this does exactly what I wanted it to do. Cheers