#### Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

# How to constrain an ellipse within Pshape shape;

edited March 2016

How can one constrain an ellipse to move with the mouse, only within the bounds created by Pshape

```Constrain c;
void setup(){
size(640,480);
c = new Constrain(10,10,300,300);
}

void draw(){
c.create();
}

class Constrain{
float xPos;
float yPos;
float Height;
float Width;
PShape s;
PImage image;
public Constrain(float x,float y,float w,float h){
xPos = x;
yPos = y;
Height = h;
Width = h;
}
void create(){
border();
pushMatrix();
translate(xPos,yPos);
s = createShape();
s.beginShape();
s.fill(53,53,53);
s.noStroke();
s.vertex(10,10);
s.vertex(30,10);
s.vertex(30,60);
s.vertex(60,60);
s.vertex(60,10);
s.vertex(90,10);
s.vertex(90,120);
s.vertex(10,120);
s.endShape(CLOSE);
shape(s);
imageMode(CENTER);
//won't work obviously, but the idea is to have the image constrained but moving with the mouse
image(image,mouseX,mouseY,20,20);
popMatrix();
}

void border(){
fill(0);
rect(xPos,yPos,Width,Height,15);
}
}

```
Tagged:

• edited March 2016

mask(), or you wanted the size, same as PShape?

• Sorry, maybe I didn't explain well. What I'd like to do is to constrain a ellipse(or circular image) with the walls of a pShape. And though it moves with the mouse, the ellipse should not move outside the walls of the pShape. I've seen this done with vectors and if only Pvector would accept PShape as a parameter, this would be easy.

• edited March 2016

Line 47: you're drawing the image between push and popMatrix(), which means you won't draw the image at the coordinates of the cursor, but ten pixels down and to the right..

Float ellipseX = mosueX, ellipseY = mouseY;

Now that you're drawing the ellipse at the correct coordinates, it'll be easier to constrain it. Next you'll ask: is the cursor inside the shape?

If the shape is an ellipse you can answer the question like this: `if (dist(shapeX,shapeY,mouseX,mouseY)<=ellipseRadius) return true;`

But if your shape is a rect you'll have to answer it like this: `if(mouseX>shapeX && mouseX <shapex+shapeWidth && mouseY>shapeY && mouseY<shapeY+shaoeHeight) return true;`

So what happens if the shape is not an ellipse and not a rect? You'll have to figure out a good way to detect if the cursor is inside. It's easier when the shape is less complex.

• edited March 2016

In my original code, I had done all that. I was able to move the ellipse/image on mouse drag when the mouse is clicked and held on the object. I scaled down the code for this forum to focus on the real problem. How do I avoid moving the object past the constrains/edges of a pShape shape e.g if I shaped up an octagon or some quadritaleral shape, and I can drag the image when clicked on , but as soon as I start dragging I want the shape to NOT move past the created shape's edges