We actually managed to edit the code so that it draws an array of box on the right side of the screen. The problem is that it only locks an image when an image is over the last box.
Code:
Sprite[] sprites;
Box[] boxes;
int bx=500;
int by=600;
int s_size=150;
boolean spritesDragging;
int boxX=640;
int boxY=100;
PImage b;
void setup()
{
size(798, 760);
boxes= new Box[7];
sprites = new Sprite[7];
for(int i = 0; i < sprites.length; i++)
{
sprites[i] = new Sprite(loadImage(i + ".png"),s_size,random(bx), random(by));
}
for(int i =0; i< boxes.length; i++)
{
boxY+=60;
boxes[i] = new Box(boxX, boxY, 140, 30);
}
}
void draw()
{
b = loadImage("EiffelTower.jpg");
background(b);
boolean bDragging = false;
//rectangle x, y, w , h
//rect(boxX, boxY, 140, 30);
for (int i=0; i <boxes.length; i++)
{
boxes[i].Draw();
}
for (int i = 0; i < sprites.length; i++)
{
// Check if the user tries to drag it
sprites[i].Update(spritesDragging);
// Ah, this one is indeed dragged!
if (sprites[i].IsDragged())
{
// We will remember a dragging is being done
bDragging = true;
// And move it to mouse position
sprites[i].Move();
}
// In all case, we redraw the sprite
sprites[i].Draw();
}
spritesDragging = bDragging;
}
class Sprite
{
float x;
float y;
PImage img;
float SpriteSize;
int i;
private boolean m_bIsHovered, m_bDragged;
private float m_clickDX, m_clickDY;
Sprite(PImage img, int SpriteSize,float x,float y)
{
this.x = x;
this.y = y;
this.img = img;
this.SpriteSize=SpriteSize;
}
void Update(boolean bAlreadyDragging)
{
// Check if mouse is over the sprite
m_bIsHovered = mouseX > x && mouseX < x + SpriteSize && mouseY > y && mouseY < y + SpriteSize/10;
if (!bAlreadyDragging && mousePressed && mouseButton == LEFT && m_bIsHovered)
{
// We record the state
m_bDragged = true;
m_clickDX = mouseX - x;
m_clickDY = mouseY - y;
}
// If mouse isn't pressed
if (!mousePressed)
{
// Any possible dragging is stopped
m_bDragged = false;
}
//method for locking image in place
if(x> boxX && x< (boxX+60) &&y <(boxY+10) && y >boxY)
{
m_bDragged = false;
}
}
boolean IsDragged()
{
return m_bDragged;
}
void Move()
{
if (m_bDragged)
{
x = mouseX - m_clickDX;
y = mouseY - m_clickDY;
}
}
void Draw()
{
image(img, x, y);
}
}
class Box
{
float x;
float y;
float h;
float w;
Box(float x,float y, float h, float w)
{
this.x = x;
this.y = y;
this.h= h;
this.w= w;
}
void Draw()
{
rect(x,y, h, w);
}
}
I believe this is because we have a for loop which increases the boxY value so then boolean which stops the dragging of an image is only recognized at the bottom box as boxY has been updated to this bottom position.
Code:
//method for locking image in place
if(x> boxX && x< (boxX+60) &&y <(boxY+10) && y >boxY)
{
m_bDragged = false;
}
Any suggestions on how to edit this?
Thanks again.