How to declare a set of points for an object to move to and from? [Android/Java] - point

What I am trying to do is create a handwriting application which allows a person to press on the object (circle) and move it up/down on a set path. If the user reaches the lowest point another circle object is created and another set of points is created to follow etc.
So far I have a onTouch event which moves my ImageView object (circle) to where ever the finger is on the touch screen.
https://gist.github.com/Temptex/9796403
How can i get my ImageView (Circle) object to go from Point A -> B smoothly using onTouch events?
Edit: A picture example of what I am asking: http://imgur.com/kjgGcba

created an algorithm for it.
Created an array of x integers and y integers and used a for loop to check if the object was to high (out of bounds in the y coordinates) and check if y and x were out of bounds in the arrays.
If it was out of bounds from the array of integers, set it to the current x/y array values. in the for loop.
If this helps anyone here is the code:
private final int yCoOrdinate[] = {310, 360, 410};
private final int xCoOrdinate[] = {905, 890, 875};
// Get finger position
int x = (int)event.getRawX();
int y = (int)event.getRawY();
// View x/y co-ordinate on TextView
coordinates.setText("X = " + x + " - Y = " + y);
for(int i = 0; i < yCoOrdinate.length; i++) {
// If object is to high set it to yCoOrdinate[0]
if(y <= yCoOrdinate[0]) {
y = yCoOrdinate[0];
}
// Checks top left corner of A
if(y == yCoOrdinate[0] && x <= xCoOrdinate[0]) {
x = xCoOrdinate[0];
Log.d("Coordinate check", "X = " + x + "Y = " + y);
// Checks if current x/y position if out of bounds and sets them to i
} else if (y <= yCoOrdinate[i] && x <= xCoOrdinate[i]) {
y = yCoOrdinate[i];
x = xCoOrdinate[i];
Log.d("Coordinate check", "X = " + x + "Y = " + y);
}
}
I can now control my ImageView with in bounds.

Related

checking edge for circular movement

I want to make my dot program turn around when they reach edge
so basically i just simply calculate
x = width/2+cos(a)*20;
y = height/2+sin(a)*20;
it's make circular movement. so i want to make this turn around by checking the edge. i also already make sure that y reach the if condition using println command
class particles {
float x, y, a, r, cosx, siny;
particles() {
x = width/2; y = height/2; a = 0; r = 20;
}
void display() {
ellipse(x, y, 20, 20);
}
void explode() {
a = a + 0.1;
cosx = cos(a)*r;
siny = sin(a)*r;
x = x + cosx;
y = y + siny;
}
void edge() {
if (x>width||x<0) cosx*=-1;
if (y>height||y<0) siny*=-1;
}
}
//setup() and draw() function
particles part;
void setup(){
size (600,400);
part = new particles();
}
void draw(){
background(40);
part.display();
part.explode();
part.edge();
}
they just ignore the if condition
There is no problem with your check, the problem is with the fact that presumably the very next time through draw() you ignore what you did in response to the check by resetting the values of cosx and siny.
I recommend creating two new variables, dx and dy ("d" for "direction") which will always be either +1 and -1 and change these variables in response to your edge check. Here is a minimal example:
float a,x,y,cosx,siny;
float dx,dy;
void setup(){
size(400,400);
background(0);
stroke(255);
noFill();
x = width/2;
y = height/2;
dx = 1;
dy = 1;
a = 0;
}
void draw(){
ellipse(x,y,10,10);
cosx = dx*20*cos(a);
siny = dy*20*sin(a);
a += 0.1;
x += cosx;
y += siny;
if (x > width || x < 0)
dx = -1*dx;
if (y > height || y < 0)
dy = -1*dy;
}
When you run this code you will observe the circles bouncing off the edges:

MissingPropertyException error (groovy)

I need to write a program that reads the X and Y coordinates of two points and then outputs the area and perimeter of a rectangle where both points are opposite corners. I however get this error message
groovy.lang.MissingPropertyException: No Such property : x for class:
rectangle.
Could anybody please help explain what is going wrong here?
// First point
Point point1 = new Point()
print "enter first x co-ordinate: "
point1.x = Double.parseDouble(System.console().readLine())
print "enter first y co-ordinate: "
point1.y = Double.parseDouble(System.console().readLine())
// Second point
Point point2 = new Point()
print "enter second x co-ordinate: "
point2.x = Double.parseDouble(System.console().readLine())
print "enter second y co-ordinate: "
point2.y = Double.parseDouble(System.console().readLine())
// Create Rectangle
Rectangle myRectangle = new Rectangle()
myRectangle.upLeft = point1
myRectangle.downRight = point2
// Calculate Perimeter
double width = myRectangle.downRight.x - myRectangle.upLeft.x
double height = myRectangle.upLeft.y - myRectangle.downRight.y
double perimeter = 2 * (width + height)
// Calculate Area
double area = width x height
println "Perimeter is " + perimeter
println "Area is " + area
class Point {
double x
double y
}
class Rectangle {
Point upLeft
Point downRight
}
You've used x instead of * in the following line:
double area = width x height
should be:
double area = width * height
Anyways script runs correctly.
The error explains itself :
No Such property : x for class: rectangle.
You are using a variable of type Rectangle and asking for property x but it doesn't exist. It's Point class which have this property.

Running cv::warpPerspective on points

I'm running the cv::warpPerspective() function on a image and what to get the position of the some points of result image the I get in the source image, here how far I came :
int main (){
cv::Point2f srcQuad[4],dstQuad[4];
cv::Mat warpMatrix;
cv::Mat src, dst,src2;
src = cv::imread("card.jpg",1);
srcQuad[0].x = 0; //src Top left
srcQuad[0].y = 0;
srcQuad[1].x = src.cols - 1; //src Top right
srcQuad[1].y = 0;
srcQuad[2].x = 0; //src Bottom left
srcQuad[2].y = src.rows - 1;
srcQuad[3].x = src.cols -1; //src Bot right
srcQuad[3].y = src.rows - 1;
dstQuad[0].x = src.cols*0.05; //dst Top left
dstQuad[0].y = src.rows*0.33;
dstQuad[1].x = src.cols*0.9; //dst Top right
dstQuad[1].y = src.rows*0.25;
dstQuad[2].x = src.cols*0.2; //dst Bottom left
dstQuad[2].y = src.rows*0.7;
dstQuad[3].x = src.cols*0.8; //dst Bot right
dstQuad[3].y = src.rows*0.9;
warpMatrix =cv::getPerspectiveTransform(srcQuad,dstQuad);
cv::warpPerspective(src,dst,warpMatrix,src.size());
cv::imshow("source", src);
cv::imshow("destination", dst);
cv::warpPerspective(dst,src2,warpMatrix,dst.size(),CV_WARP_INVERSE_MAP);
cv::imshow("srouce 2 " , src2);
cv::waitKey();
return 0;
my problem is that if I select a point from dst how can get its coordinates in ** src or src2 ** since the cv::warpPerspective function doesn't take cv::Point as parameter ??
You want perspectiveTransform (which works on a vector of Points) rather than warpPerspective.
Take the inverse of warpMatrix; you may have to tweak the final column.
vector<Point2f> dstPoints, srcPoints;
dstPoints.push_back(Point2f(1,1));
cv::perspectiveTransform(dstPoints,srcPoints,warpMatrix.inv());
A perspective transform relates two points in the following manner:
[x'] [m00 m01 m02] [x]
[y'] = [m10 m11 m12] [y]
[1] [m20 m21 m22] [1]
Where (x,y) are the original 2D point coordinates, and (x', y') are the transformed coordinates.
In your case, you know (x', y'), and want to know (x, y). This can be achieved by multiplying the known point by the inverse of the transformation matrix:
cv::Matx33f warp = warpMatrix; // cv::Matx is much more useful for math
cv::Point2f warped_point = dstQuad[3]; // I just use dstQuad as an example
cv::Point3f homogeneous = warp.inv() * warped_point;
cv::Point2f result(homogeneous.x, homogeneous.y); // Drop the z=1 to get out of homogeneous coordinates
// now, result == srcQuad[3], which is what you wanted

Getting Depth of other objects Kinect

I'm a newbie in kinect programming, i am working on a ball tracking using kinect and opencv..we all know that kinect provides Depth data, and with the code below:
DepthImagePoint righthandDepthPoint =
sensor.CoordinateMapper.MapSkeletonPointToDepthPoint
(
me.Joints[JointType.HandRight].Position,
DepthImageFormat.Resolution640x480Fps30
);
double rightdepthmeters = (righthandDepthPoint.Depth);
using this, I am able to get the depth of a right hand, using the function MapSkeletonPointToDepthPoint() by specifing the jointtype..
Is it possible to get the depth of other objects by specifying in the image where?
given the coordinate..I want to get the depth of the object in that coordinate?
Pulling depth data from the Kinect SDK can be extracted from the DepthImagePixel structure.
The example code below loops through the entire DepthImageFrame to examine each of the pixels. If you have a specific coordinate you wish to look at, remove the for loop and set the x and y to a specific value.
// global variables
private const DepthImageFormat DepthFormat = DepthImageFormat.Resolution320x240Fps30;
private const ColorImageFormat ColorFormat = ColorImageFormat.RgbResolution640x480Fps30;
private DepthImagePixel[] depthPixels;
// defined in an initialization function
this.depthWidth = this.sensor.DepthStream.FrameWidth;
this.depthHeight = this.sensor.DepthStream.FrameHeight;
this.depthPixels = new DepthImagePixel[this.sensor.DepthStream.FramePixelDataLength];
private void SensorAllFramesReady(object sender, AllFramesReadyEventArgs e)
{
if (null == this.sensor)
return;
bool depthReceived = false;
using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
{
if (null != depthFrame)
{
// Copy the pixel data from the image to a temporary array
depthFrame.CopyDepthImagePixelDataTo(this.depthPixels);
depthReceived = true;
}
}
if (true == depthReceived)
{
// loop over each row and column of the depth
for (int y = 0; y < this.depthHeight; ++y)
{
for (int x = 0; x < this.depthWidth; ++x)
{
// calculate index into depth array
int depthIndex = x + (y * this.depthWidth);
// extract the given index
DepthImagePixel depthPixel = this.depthPixels[depthIndex];
Debug.WriteLine("Depth at [" + x + ", " + y + "] is: " + depthPixel.Depth);
}
}
}
}

How to test if a line segment intersects an axis-aligned rectange in 2D?

How to test if a line segment intersects an axis-aligned rectange in 2D? The segment is defined with its two ends: p1, p2. The rectangle is defined with top-left and bottom-right points.
The original poster wanted to DETECT an intersection between a line segment and a polygon. There was no need to LOCATE the intersection, if there is one. If that's how you meant it, you can do less work than Liang-Barsky or Cohen-Sutherland:
Let the segment endpoints be p1=(x1 y1) and p2=(x2 y2).
Let the rectangle's corners be (xBL yBL) and (xTR yTR).
Then all you have to do is
A. Check if all four corners of the rectangle are on the same side of the line.
The implicit equation for a line through p1 and p2 is:
F(x y) = (y2-y1)*x + (x1-x2)*y + (x2*y1-x1*y2)
If F(x y) = 0, (x y) is ON the line.
If F(x y) > 0, (x y) is "above" the line.
If F(x y) < 0, (x y) is "below" the line.
Substitute all four corners into F(x y). If they're all negative or all positive, there is no intersection. If some are positive and some negative, go to step B.
B. Project the endpoint onto the x axis, and check if the segment's shadow intersects the polygon's shadow. Repeat on the y axis:
If (x1 > xTR and x2 > xTR), no intersection (line is to right of rectangle).
If (x1 < xBL and x2 < xBL), no intersection (line is to left of rectangle).
If (y1 > yTR and y2 > yTR), no intersection (line is above rectangle).
If (y1 < yBL and y2 < yBL), no intersection (line is below rectangle).
else, there is an intersection. Do Cohen-Sutherland or whatever code was mentioned in the other answers to your question.
You can, of course, do B first, then A.
Alejo
Wrote quite simple and working solution:
bool SegmentIntersectRectangle(double a_rectangleMinX,
double a_rectangleMinY,
double a_rectangleMaxX,
double a_rectangleMaxY,
double a_p1x,
double a_p1y,
double a_p2x,
double a_p2y)
{
// Find min and max X for the segment
double minX = a_p1x;
double maxX = a_p2x;
if(a_p1x > a_p2x)
{
minX = a_p2x;
maxX = a_p1x;
}
// Find the intersection of the segment's and rectangle's x-projections
if(maxX > a_rectangleMaxX)
{
maxX = a_rectangleMaxX;
}
if(minX < a_rectangleMinX)
{
minX = a_rectangleMinX;
}
if(minX > maxX) // If their projections do not intersect return false
{
return false;
}
// Find corresponding min and max Y for min and max X we found before
double minY = a_p1y;
double maxY = a_p2y;
double dx = a_p2x - a_p1x;
if(Math::Abs(dx) > 0.0000001)
{
double a = (a_p2y - a_p1y) / dx;
double b = a_p1y - a * a_p1x;
minY = a * minX + b;
maxY = a * maxX + b;
}
if(minY > maxY)
{
double tmp = maxY;
maxY = minY;
minY = tmp;
}
// Find the intersection of the segment's and rectangle's y-projections
if(maxY > a_rectangleMaxY)
{
maxY = a_rectangleMaxY;
}
if(minY < a_rectangleMinY)
{
minY = a_rectangleMinY;
}
if(minY > maxY) // If Y-projections do not intersect return false
{
return false;
}
return true;
}
Since your rectangle is aligned, Liang-Barsky might be a good solution. It is faster than Cohen-Sutherland, if speed is significant here.
Siggraph explanation
Another good description
And of course, Wikipedia
You could also create a rectangle out of the segment and test if the other rectangle collides with it, since it is just a series of comparisons. From pygame source:
def _rect_collide(a, b):
return a.x + a.w > b.x and b.x + b.w > a.x and \
a.y + a.h > b.y and b.y + b.h > a.y
Use the Cohen-Sutherland algorithm.
It's used for clipping but can be slightly tweaked for this task. It divides 2D space up into a tic-tac-toe board with your rectangle as the "center square".
then it checks to see which of the nine regions each of your line's two points are in.
If both points are left, right, top, or bottom, you trivially reject.
If either point is inside, you trivially accept.
In the rare remaining cases you can do the math to intersect with whichever sides of the rectangle are possible to intersect with, based on which regions they're in.
Or just use/copy the code already in the Java method
java.awt.geom.Rectangle2D.intersectsLine(double x1, double y1, double x2, double y2)
Here is the method after being converted to static for convenience:
/**
* Code copied from {#link java.awt.geom.Rectangle2D#intersectsLine(double, double, double, double)}
*/
public class RectangleLineIntersectTest {
private static final int OUT_LEFT = 1;
private static final int OUT_TOP = 2;
private static final int OUT_RIGHT = 4;
private static final int OUT_BOTTOM = 8;
private static int outcode(double pX, double pY, double rectX, double rectY, double rectWidth, double rectHeight) {
int out = 0;
if (rectWidth <= 0) {
out |= OUT_LEFT | OUT_RIGHT;
} else if (pX < rectX) {
out |= OUT_LEFT;
} else if (pX > rectX + rectWidth) {
out |= OUT_RIGHT;
}
if (rectHeight <= 0) {
out |= OUT_TOP | OUT_BOTTOM;
} else if (pY < rectY) {
out |= OUT_TOP;
} else if (pY > rectY + rectHeight) {
out |= OUT_BOTTOM;
}
return out;
}
public static boolean intersectsLine(double lineX1, double lineY1, double lineX2, double lineY2, double rectX, double rectY, double rectWidth, double rectHeight) {
int out1, out2;
if ((out2 = outcode(lineX2, lineY2, rectX, rectY, rectWidth, rectHeight)) == 0) {
return true;
}
while ((out1 = outcode(lineX1, lineY1, rectX, rectY, rectWidth, rectHeight)) != 0) {
if ((out1 & out2) != 0) {
return false;
}
if ((out1 & (OUT_LEFT | OUT_RIGHT)) != 0) {
double x = rectX;
if ((out1 & OUT_RIGHT) != 0) {
x += rectWidth;
}
lineY1 = lineY1 + (x - lineX1) * (lineY2 - lineY1) / (lineX2 - lineX1);
lineX1 = x;
} else {
double y = rectY;
if ((out1 & OUT_BOTTOM) != 0) {
y += rectHeight;
}
lineX1 = lineX1 + (y - lineY1) * (lineX2 - lineX1) / (lineY2 - lineY1);
lineY1 = y;
}
}
return true;
}
}
A quick Google search popped up a page with C++ code for testing the intersection.
Basically it tests the intersection between the line, and every border or the rectangle.
Rectangle and line intersection code
Here's a javascript version of #metamal's answer
var isRectangleIntersectedByLine = function (
a_rectangleMinX,
a_rectangleMinY,
a_rectangleMaxX,
a_rectangleMaxY,
a_p1x,
a_p1y,
a_p2x,
a_p2y) {
// Find min and max X for the segment
var minX = a_p1x
var maxX = a_p2x
if (a_p1x > a_p2x) {
minX = a_p2x
maxX = a_p1x
}
// Find the intersection of the segment's and rectangle's x-projections
if (maxX > a_rectangleMaxX)
maxX = a_rectangleMaxX
if (minX < a_rectangleMinX)
minX = a_rectangleMinX
// If their projections do not intersect return false
if (minX > maxX)
return false
// Find corresponding min and max Y for min and max X we found before
var minY = a_p1y
var maxY = a_p2y
var dx = a_p2x - a_p1x
if (Math.abs(dx) > 0.0000001) {
var a = (a_p2y - a_p1y) / dx
var b = a_p1y - a * a_p1x
minY = a * minX + b
maxY = a * maxX + b
}
if (minY > maxY) {
var tmp = maxY
maxY = minY
minY = tmp
}
// Find the intersection of the segment's and rectangle's y-projections
if(maxY > a_rectangleMaxY)
maxY = a_rectangleMaxY
if (minY < a_rectangleMinY)
minY = a_rectangleMinY
// If Y-projections do not intersect return false
if(minY > maxY)
return false
return true
}
I did a little napkin solution..
Next find m and c and hence the equation y = mx + c
y = (Point2.Y - Point1.Y) / (Point2.X - Point1.X)
Substitute P1 co-ordinates to now find c
Now for a rectangle vertex, put the X value in the line equation, get the Y value and see if the Y value lies in the rectangle bounds shown below
(you can find the constant values X1, X2, Y1, Y2 for the rectangle such that)
X1 <= x <= X2 &
Y1 <= y <= Y2
If the Y value satisfies the above condition and lies between (Point1.Y, Point2.Y) - we have an intersection.
Try every vertex if this one fails to make the cut.
I was looking at a similar problem and here's what I came up with. I was first comparing the edges and realized something. If the midpoint of an edge that fell within the opposite axis of the first box is within half the length of that edge of the outer points on the first in the same axis, then there is an intersection of that side somewhere.
But that was thinking 1 dimensionally and required looking at each side of the second box to figure out.
It suddenly occurred to me that if you find the 'midpoint' of the second box and compare the coordinates of the midpoint to see if they fall within 1/2 length of a side (of the second box) of the outer dimensions of the first, then there is an intersection somewhere.
i.e. box 1 is bounded by x1,y1 to x2,y2
box 2 is bounded by a1,b1 to a2,b2
the width and height of box 2 is:
w2 = a2 - a1 (half of that is w2/2)
h2 = b2 - b1 (half of that is h2/2)
the midpoints of box 2 are:
am = a1 + w2/2
bm = b1 + h2/2
So now you just check if
(x1 - w2/2) < am < (x2 + w2/2) and (y1 - h2/2) < bm < (y2 + h2/2)
then the two overlap somewhere.
If you want to check also for edges intersecting to count as 'overlap' then
change the < to <=
Of course you could just as easily compare the other way around (checking midpoints of box1 to be within 1/2 length of the outer dimenions of box 2)
And even more simplification - shift the midpoint by your half lengths and it's identical to the origin point of that box. Which means you can now check just that point for falling within your bounding range and by shifting the plain up and to the left, the lower corner is now the lower corner of the first box. Much less math:
(x1 - w2) < a1 < x2
&&
(y1 - h2) < b1 < y2
[overlap exists]
or non-substituted:
( (x1-(a2-a1)) < a1 < x2 ) && ( (y1-(b2-b1)) < b1 < y2 ) [overlap exists]
( (x1-(a2-a1)) <= a1 <= x2 ) && ( (y1-(b2-b1)) <= b1 <= y2 ) [overlap or intersect exists]
coding example in PHP (I'm using an object model that has methods for things like getLeft(), getRight(), getTop(), getBottom() to get the outer coordinates of a polygon and also has a getWidth() and getHeight() - depending on what parameters were fed it, it will calculate and cache the unknowns - i.e. I can create a polygon with x1,y1 and ... w,h or x2,y2 and it can calculate the others)
I use 'n' to designate the 'new' item being checked for overlap ($nItem is an instance of my polygon object) - the items to be tested again [this is a bin/sort knapsack program] are in an array consisting of more instances of the (same) polygon object.
public function checkForOverlaps(BinPack_Polygon $nItem) {
// grab some local variables for the stuff re-used over and over in loop
$nX = $nItem->getLeft();
$nY = $nItem->getTop();
$nW = $nItem->getWidth();
$nH = $nItem->getHeight();
// loop through the stored polygons checking for overlaps
foreach($this->packed as $_i => $pI) {
if(((($pI->getLeft() - $nW) < $nX) && ($nX < $pI->getRight())) &&
((($pI->getTop() - $nH) < $nY) && ($nY < $pI->getBottom()))) {
return false;
}
}
return true;
}
Some sample code for my solution (in php):
// returns 'true' on overlap checking against an array of similar objects in $this->packed
public function checkForOverlaps(BinPack_Polygon $nItem) {
$nX = $nItem->getLeft();
$nY = $nItem->getTop();
$nW = $nItem->getWidth();
$nH = $nItem->getHeight();
// loop through the stored polygons checking for overlaps
foreach($this->packed as $_i => $pI) {
if(((($pI->getLeft() - $nW) < $nX) && ($nX < $pI->getRight())) && ((($pI->getTop() - $nH) < $nY) && ($nY < $pI->getBottom()))) {
return true;
}
}
return false;
}

Resources