Does a line contain a point - android

I want the user to be able to drag the edges of a square around the canvas. With my current solution it works but has glitches, sometimes an edge cannot be selected. Is there a clean way to tell if a line has been clicked (e.g. passes through a coordinate)? This is how I'm currently testing:
// check edge pressed, edge is the line between to
// coords e.g. (i) & (i = 1)
for (int i = 0; i < coords.size(); i++) {
p1 = coords.get(i);
if ((i + 1) > (coords.size() - 1)) p2 = coords.get(0);
else p2 = coords.get(i + 1);
// is this the line pressed
if (p1.x <= event.getX() + 5 && event.getX() - 5 <= p2.x && p1.y <= event.getY() + 5 && event.getY() - 5 <= p2.y) {
// points found, set to non temp
// variable for use in ACTION_MOVE
point1 = p1;
point2 = p2;
break;
} else if (p1.x >= event.getX() + 5 && event.getX() - 5 >= p2.x && p1.y >= event.getY() + 5 && event.getY() - 5 >= p2.y) {
// points found, set to non temp
// variable for use in ACTION_MOVE
point1 = p1;
point2 = p2;
break;
}
}
The code bellow //is this the line pressed is the most important and also most likely the issue. The +5 and -5 are used to give the use a larger area to click on.
Here is the whole on click event:
public void EditEdge() {
//TODO this works like shit
// Detect the two coordinates along the edge pressed and drag
// them
scene.setOnTouchListener(new View.OnTouchListener() {
private int startX;
private int startY;
private Point point1 = new Point(0, 0);
private Point point2 = new Point(0, 0);
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = (int) event.getX();
startY = (int) event.getY();
Point p1;
Point p2;
// check edge pressed, edge is the line between to
// coords e.g. (i) & (i = 1)
for (int i = 0; i < coords.size(); i++) {
p1 = coords.get(i);
if ((i + 1) > (coords.size() - 1)) p2 = coords.get(0);
else p2 = coords.get(i + 1);
// is this the line pressed
if (p1.x <= event.getX() + 5 && event.getX() - 5 <= p2.x && p1.y <= event.getY() + 5 && event.getY() - 5 <= p2.y) {
// points found, set to non temp
// variable for use in ACTION_MOVE
point1 = p1;
point2 = p2;
break;
} else if (p1.x >= event.getX() + 5 && event.getX() - 5 >= p2.x && p1.y >= event.getY() + 5 && event.getY() - 5 >= p2.y) {
// points found, set to non temp
// variable for use in ACTION_MOVE
point1 = p1;
point2 = p2;
break;
}
}
break;
case MotionEvent.ACTION_UP:
point1 = new Point(0, 0);
point2 = new Point(0, 0);
// scene.setOnTouchListener(scene.editModeOnTouchListener);
break;
case MotionEvent.ACTION_MOVE:
for (Point p: new Point[] {
point1, point2
}) {
int modX = (int)(p.x + (event.getX() - startX));
int modY = (int)(p.y + (event.getY() - startY));
p.set(modX, modY);
}
SetCoords(coords);
startX = (int) event.getX();
startY = (int) event.getY();
break;
default:
return false;
}
return true;
}
});
}
So is there a easier way to tell is a line is clicked/ passes through a point or is that not the issue?
Thanks

use the line equation y = mx + b to find out if the point is on a line
float EPSILON = 0.001f;
public boolean isPointOnLine(Point linePointA, Point linePointB, Point point) {
float m = (linePointB.y - linePointA.y) / (linePointB.x - linePointA.x);
float b = linePointA.y - m * linePointA.x;
return Math.abs(point.y - (m*point.x+b)) < EPSILON);
}

Great piece of code by #tyczj !
I added a use-case to handle vertical lines, which gives me the following code fragment:
public boolean isPointOnLine(PointF lineStaPt, PointF lineEndPt, PointF point) {
final float EPSILON = 0.001f;
if (Math.abs(staPt.x - endPt.x) < EPSILON) {
// We've a vertical line, thus check only the x-value of the point.
return (Math.abs(point.x - lineStaPt.x) < EPSILON);
} else {
float m = (lineEndPt.y - lineStaPt.y) / (lineEndPt.x - lineStaPt.x);
float b = lineStaPt.y - m * lineStaPt.x;
return (Math.abs(point.y - (m * point.x + b)) < EPSILON);
}
}
Also a piece of code to check if a point lies on a line-segment:
public boolean isPointOnLineSegment(PointF staPt, PointF endPt, PointF point) {
final float EPSILON = 0.001f;
if (isPointOnLine(staPt, endPt, point)) {
// Create lineSegment bounding-box.
RectF lb = new RectF(staPt.x, staPt.y, endPt.x, endPt.y);
// Extend bounds with epsilon.
RectF bounds = new RectF(lb.left - EPSILON, lb.top - EPSILON, lb.right + EPSILON, lb.bottom + EPSILON);
// Check if point is contained within lineSegment-bounds.
return bounds.contains(point.x, point.y);
}
return false;
}

You could define 8 Rect to check against - the 4 sides and 4 corners (so you can move 2 edges at once). The lines of the edge should have a width for the touchable area.
Define a Point centred on your touch event, there are then methods for checking if a rect contains a point.

Related

How to recognize touch on a triangle?

I'm trying to recognize if the (x,y) of my finger is touching any part of the triangle object.
This is how I draw the triangle
public void drawTriangle(Canvas canvas, Paint paint, int x, int y, int width) {
int halfWidth = width / 2;
Path path = new Path();
path.moveTo(x, y - halfWidth); // Top
path.lineTo(x - halfWidth, y + halfWidth); // Bottom left
path.lineTo(x + halfWidth, y + halfWidth); // Bottom right
path.lineTo(x, y - halfWidth); // Back to Top
path.close();
canvas.drawPath(path, paint);
}
This is how I draw to the screen + examples of how I recognize other shapes like square and circle:
public boolean onTouchEvent(MotionEvent event) {
int X = (int) event.getX();
int Y = (int) event.getY();
int eventaction = event.getAction();
switch (eventaction) {
/*
case MotionEvent.ACTION_DOWN:
Toast.makeText(this, "ACTION_DOWN AT COORDS "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show();
isTouch = true;
break;
*/
case MotionEvent.ACTION_MOVE:
{
int s = triangle.getY() * triangle.getWidth()/ triangle.getY()-triangle.getWidth()/2;
if(X>=circle.getX()-circle.getRadius()&&X<=circle.getX()+circle.getRadius()
&&Y>=circle.getY()-circle.getRadius()&&Y<=circle.getY()+circle.getRadius()) {
circle.setX(X);
circle.setY(Y);
//square.setX(X);
//square.setY(Y);
}
if(X < square.getX() + square.getWidth() && X + square.getWidth() > square.getX() &&
Y < square.getY() + square.getHeight() && Y + square.getHeight() > square.getY())
{
square.setX(X);
square.setY(Y);
}
if(//triangle help)
{
triangle.setX(X);
triangle.setY(Y);
}
break;
}
}
return true;
}
Source link of pseudocode solution.
There are multiple ways to check if the point is in or out of a triangle.
Let's say that each of the vertices of a triangle has inner and outer sides. Inner is the one that is inside of a triangle, outer is therefore outside of a triangle.
To check if a point is inside of a triangle we can check if the point is on the inner side of each triangle vertex.
Note: this solution might require some minor changes from you as I do not know the exact structure of your triangle class.
public boolean onTouchEvent(MotionEvent event) {
int X = (int) event.getX();
int Y = (int) event.getY();
int eventaction = event.getAction();
switch (eventaction) {
case MotionEvent.ACTION_MOVE:
{
...
int halfWidth = triangle.getWidth()/2;
Pair<Integer, Integer> v1 = new Pair(triangle.getX(), triangle.getY() - halfWidth);
Pair<Integer, Integer> v2 = new Pair(triangle.getX() - halfWidth, triangle.getY() + haldWidth);
Pair<Integer, Integer> v3 = new Pair(triangle.getX() + halfWidth, triangle.getY() + halfWidth);
if (isPointInTriangle(x, y, v1, v2, v3)) {
// point is inside of a triangle
}
break;
}
}
return true;
}
private int sign(int x, int y, Pair<Integer, Integer> vertex1, Pair<Integer, Integer> vertex2) {
return (x - vertex2.first) * (vertex1.second - vertex2.second) - (vertex1.first - vertex2.first) * (y - vertex2.second);
}
private boolean isPointInTriangle(int x, int y, Pair<Integer, Integer> vertex1, Pair<Integer, Integer> vertex2, Pair<Integer, Integer> vertex3)
{
int r1 = sign(x, y, vertex1, vertex2);
int r2 = sign(x, y, vertex2, vertex3);
int r3 = sign(x, y, vertex3, vertex1);
boolean hasNegative = (r1 < 0) || (r2 < 0) || (r3 < 0);
boolean hasPositive = (r1 > 0) || (r2 > 0) || (r3 > 0);
return !(hasNegative && hasPositive);
}
Here is what I would do to recognize them:
1- Every shape I draw will have its coordinates saved in a list (example: a circle has a center and a radius). These coordinates can help you to decide if a given touch coordinate is touching a shape. You can use a list by shape if you want to know the type of the shape.
2- Whenever you will touch a portion of the canvas, you will get the coordinates of this touched part, then go through the saved shapes and check if the coordinates are on/in (sorry I am french speaking) the shape. So the thing now it that you will have to check the algorithms that will allow you to know when a coordinate/point is on/in a shape.

Android Gyroscope for tilting

Thanks in advance for your help first.
I have found so many examples using Gyroscope. But I couldn't find adequate one for me.
I'd like to make a simple quiz game that do actions when I tilt VM to 90 degrees forward and backward. Many examples said I might use "pitch" value of Gyroscope. Could you give some advices for me??
I have done a similar thing where i need draw a rectangle with includes nearby places and must point it to the place and show details.
public void onSensorChanged(SensorEvent event) {
final Handler handler = new Handler();
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
mAcceleromterReading =
SensorUtilities.filterSensors(event.values, mAcceleromterReading);
break;
case Sensor.TYPE_MAGNETIC_FIELD:
mMagnetometerReading =
SensorUtilities.filterSensors(event.values, mMagnetometerReading);
break;
float[] orientation =
SensorUtilities.computeDeviceOrientation(mAcceleromterReading, mMagnetometerReading);
if (orientation != null) {
float azimuth = (float) Math.toDegrees(orientation[0]);
if (azimuth < 0) {
azimuth += 360f;
}
// Convert pitch and roll from radians to degrees
float pitch = (float) Math.toDegrees(orientation[1]);
float roll = (float) Math.toDegrees(orientation[2]);
if (abs(pitch - pitchPrev) > PITCH_THRESHOLD && abs(roll - rollPrev) > ROLL_THRESHOLD
&& abs(azimuth - azimuthPrev) > AZIMUTH_THRESHOLD) { // && abs(roll - rollPrev) > rollThreshold
if (DashplexManager.getInstance().mlocation != null) {
mOverlayDisplayView.setHorizontalFOV(mPreview.getHorizontalFOV());
mOverlayDisplayView.setVerticalFOV(mPreview.getVerticalFOV());
mOverlayDisplayView.setAzimuth(azimuth);
mOverlayDisplayView.setPitch(pitch);
mOverlayDisplayView.setRoll(roll);
// Update the OverlayDisplayView to red raw when sensor dataLogin changes,
// redrawing only when the camera is not pointing straight up or down
if (pitch <= 75 && pitch >= -75) {
//Log.d("issueAR", "invalidate: ");
mOverlayDisplayView.invalidate();
}
}
pitchPrev = pitch;
rollPrev = roll;
azimuthPrev = azimuth;
}
}
computeDeviceOrientation method
public static float[] computeDeviceOrientation(float[] accelerometerReading, float[] magnetometerReading) {
if (accelerometerReading == null || magnetometerReading == null) {
return null;
}
final float[] rotationMatrix = new float[9];
SensorManager.getRotationMatrix(rotationMatrix, null, accelerometerReading, magnetometerReading);
// Remap the coordinates with the camera pointing along the Y axis.
// This way, portrait and landscape orientation return the same azimuth to magnetic north.
final float cameraRotationMatrix[] = new float[9];
SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_X,
SensorManager.AXIS_Z, cameraRotationMatrix);
final float[] orientationAngles = new float[3];
SensorManager.getOrientation(cameraRotationMatrix, orientationAngles);
// Return a float array containing [azimuth, pitch, roll]
return orientationAngles;
}
onDraw method
#SuppressLint("DrawAllocation")
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Log.d("issueAR", "onDraw: ");
// Log.d("issueAR", "mVerticalFOV: "+mVerticalFOV+" "+"mHorizontalFOV"+mHorizontalFOV);
// Get the viewports only once
if (!mGotViewports && mVerticalFOV > 0 && mHorizontalFOV > 0) {
mViewportHeight = canvas.getHeight() / mVerticalFOV;
mViewportWidth = canvas.getWidth() / mHorizontalFOV;
mGotViewports = true;
//Log.d("onDraw", "mViewportHeight: " + mViewportHeight);
}
if (!mGotViewports) {
return;
}
// Set the paints that remain constant only once
if (!mSetPaints) {
mTextPaint.setTextAlign(Paint.Align.LEFT);
mTextPaint.setTextSize(getResources().getDimensionPixelSize(R.dimen.canvas_text_size));
mTextPaint.setColor(Color.WHITE);
mOutlinePaint.setStyle(Paint.Style.STROKE);
mOutlinePaint.setStrokeWidth(mOutline);
mBubblePaint.setStyle(Paint.Style.FILL);
mSetPaints = true;
}
// Center of view
float x = canvas.getWidth() / 2;
float y = canvas.getHeight() / 2;
/*
* Uncomment line below to allow rotation of display around the center point
* based on the roll. However, this "feature" is not very intuitive, and requires
* locking device orientation to portrait or changes the sensor rotation matrix
* on device rotation. It's really quite a nightmare.
*/
//canvas.rotate((0.0f - mRoll), x, y);
float dy = mPitch * mViewportHeight;
if (mNearbyPlaces != null) {
//Log.d("OverlayDisplayView", "mNearbyPlaces: "+mNearbyPlaces.size());
// Iterate backwards to draw more distant places first
for (int i = mNearbyPlaces.size() - 1; i >= 0; i--) {
NearbyPlace nearbyPlace = mNearbyPlaces.get(i);
float xDegreesToTarget = mAzimuth - nearbyPlace.getBearingToPlace();
float dx = mViewportWidth * xDegreesToTarget;
float iconX = x - dx;
float iconY = y - dy;
if (isOverlapping(iconX, iconX).isOverlapped()) {
PointF point = calculateNewXY(new PointF(iconX, iconY + mViewportHeight));
iconX = point.x;
iconY = point.y;
}
nearbyPlace.setIconX(iconX);
nearbyPlace.setIconY(iconY);
Bitmap icon = getIcon(nearbyPlace.getIcon_id());
float width = icon.getWidth() + mTextPaint.measureText(nearbyPlace.getName()) + mMargin;
RectF recf=new RectF(iconX, iconY, width, icon.getHeight());
nearbyPlace.setRect(recf);
float angleToTarget = xDegreesToTarget;
if (xDegreesToTarget < 0) {
angleToTarget = 360 + xDegreesToTarget;
}
if (angleToTarget >= 0 && angleToTarget < 90) {
nearbyPlace.setQuadrant(1);
mQuad1Places.add(nearbyPlace);
} else if (angleToTarget >= 90 && angleToTarget < 180) {
nearbyPlace.setQuadrant(2);
mQuad2Places.add(nearbyPlace);
} else if (angleToTarget >= 180 && angleToTarget < 270) {
nearbyPlace.setQuadrant(3);
mQuad3Places.add(nearbyPlace);
} else {
nearbyPlace.setQuadrant(4);
mQuad4Places.add(nearbyPlace);
}
//Log.d("TAG", " - X: " + iconX + " y: " + iconY + " angle: " + angleToTarget + " display: " + nearbyPlace.getIcon_id());
}
drawQuadrant(mQuad1Places, canvas);
drawQuadrant(mQuad2Places, canvas);
drawQuadrant(mQuad3Places, canvas);
drawQuadrant(mQuad4Places, canvas);
}
}
It doesnot contain full code, but you may understand how pitch and azimuth with roll is used.. Best of luck

Multitouch Canvas Rotation in Android

I'm new to Android, and I'm trying to get the hang of multi touch input. I've begun with a simple app that allows the user to create rectangles on a Canvas by dragging and releasing with one finger, which I have working. To expand upon that, I now want a user to be able to rotate the rectangle they are drawing using a second finger, which is where my problems begin. As it stands, adding a second finger will cause multiple rectangles to rotate, instead of just the current one, but they will revert to their default orientation as soon as the second finger is released.
I've been working at it for a while, and I think my core problem is that I'm mishandling the multiple MotionEvents that come with two (or more fingers). Logging statements I left to display the coordinates on the screen for each event stay tied to the first finger touching the screen, instead of switching to the second. I've tried multiple configurations of accessing and changing the event pointer ID, and still no luck. If anyone could provide some guidance in the right direction, I would be extremely grateful.
My code is as follows:
public class BoxDrawingView extends View {
private static final String TAG = "BoxDrawingView";
private static final int INVALID_POINTER_ID = -1;
private int mActivePointerId = INVALID_POINTER_ID;
private Box mCurrentBox;
private List<Box> mBoxen = new ArrayList<>();
private Float mLastTouchX;
private Float mLastTouchY;
...
#Override
public boolean onTouchEvent(MotionEvent event) {
switch(MotionEventCompat.getActionMasked(event)) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = MotionEventCompat.getPointerId(event, 0);
current = new PointF(MotionEventCompat.getX(event, mActivePointerId),
MotionEventCompat.getY(event, mActivePointerId));
action = "ACTION_DOWN";
// Reset drawing state
mCurrentBox = new Box(current);
mBoxen.add(mCurrentBox);
mLastTouchX = MotionEventCompat.getX(event, MotionEventCompat.getPointerId(event, 0));
mLastTouchY = MotionEventCompat.getY(event, MotionEventCompat.getPointerId(event, 0));
break;
case MotionEvent.ACTION_POINTER_DOWN:
action = "ACTION_POINTER_DOWN";
mActivePointerId = MotionEventCompat.getPointerId(event, 0);
mLastTouchX = MotionEventCompat.getX(event, MotionEventCompat.getPointerId(event, 0));
mLastTouchY = MotionEventCompat.getY(event, MotionEventCompat.getPointerId(event, 0));
break;
case MotionEvent.ACTION_MOVE:
action = "ACTION_MOVE";
current = new PointF(MotionEventCompat.getX(event, mActivePointerId),
MotionEventCompat.getY(event, mActivePointerId));
if (mCurrentBox != null) {
mCurrentBox.setCurrent(current);
invalidate();
}
if(MotionEventCompat.getPointerCount(event) > 1) {
int pointerIndex = MotionEventCompat.findPointerIndex(event, mActivePointerId);
float currX = MotionEventCompat.getX(event, pointerIndex);
float currY = MotionEventCompat.getY(event, pointerIndex);
if(mLastTouchX < currX) {
// simplified: only use x coordinates for rotation for now.
// +X for clockwise, -X for counter clockwise
Log.d(TAG, "Clockwise");
mRotationAngle = 30;
}
else if (mLastTouchX > getX()) {
Log.d(TAG, "Counter clockwise");
mRotationAngle = -30;
}
}
break;
case MotionEvent.ACTION_UP:
action = "ACTION_UP";
mCurrentBox = null;
mLastTouchX = null;
mLastTouchY = null;
mActivePointerId = INVALID_POINTER_ID;
break;
case MotionEvent.ACTION_POINTER_UP:
action = "ACTION_POINTER_UP";
int pointerIndex = event.getActionIndex();
int pointerId = event.getPointerId(pointerIndex);
if(pointerId == mActivePointerId){
mActivePointerId = INVALID_POINTER_ID;
}
break;
case MotionEvent.ACTION_CANCEL:
action = "ACTION_CANCEL";
mCurrentBox = null;
mActivePointerId = INVALID_POINTER_ID;
break;
}
return true;
}
#Override
protected void onDraw(Canvas canvas){
// Fill the background
canvas.drawPaint(mBackgroundPaint);
for(Box box : mBoxen) {
// Box is a custom object. Origin is the origin point,
// Current is the point of the opposite diagonal corner
float left = Math.min(box.getOrigin().x, box.getCurrent().x);
float right = Math.max(box.getOrigin().x, box.getCurrent().x);
float top = Math.min(box.getOrigin().y, box.getCurrent().y);
float bottom = Math.max(box.getOrigin().y, box.getCurrent().y);
if(mRotationAngle != 0) {
canvas.save();
canvas.rotate(mRotationAngle);
canvas.drawRect(left, top, right, bottom, mBoxPaint);
canvas.rotate(-mRotationAngle);
canvas.restore();
mRotationAngle = 0;
} else {
canvas.drawRect(left, top, right, bottom, mBoxPaint);
}
}
}
}
There are several ways to draw things, not just in android, but in Java as well. The thing is that you are trying to draw the rectangles by rotating the Canvas. That's a way, but in my personal experience I think that is only a good choice if you want to rotate the whole picture. If not, that may get a little tricky because you need to place a rotation axis, which it seems you are not using, so Android will asume that you want to rotate from the left top corner or the center of the view (I don't remember).
If you are opting for that choice, you may try to do it like this:
Matrix matrix = new Matrix();
matrix.setRotate(angle, rectangleCenterX, rectangleCenterY);
canvas.setMatrix(matrix);
But I recommend you to try a different approach. Do the rotation directly on the rectangle that you are moving, by calculating the axes of the polygon. This you can do it using Java Math operations:
public void formShape(int cx[], int cy[], double scale) {
double xGap = (width / 2) * Math.cos(angle) * scale;
double yGap = (width / 2) * Math.sin(angle) * scale;
cx[0] = (int) (x * scale + xGap);
cy[0] = (int) (y * scale + yGap);
cx[1] = (int) (x * scale - xGap);
cy[1] = (int) (y * scale - yGap);
cx[2] = (int) (x * scale - xGap - length * Math.cos(radians) * scale);
cy[2] = (int) (y * scale - yGap - length * Math.sin(radians) * scale);
cx[3] = (int) (x * scale + xGap - length * Math.cos(radians) * scale);
cy[3] = (int) (y * scale + yGap - length * Math.sin(radians) * scale);
}
So (x,y) is the center of your rectangle and with, height tell you how big is it. In the formShape(int[], int[], double) method cx and cy are going to be used to draw your shape and scale is the value to use if you want to do zoom in or zoom out later, if not just use scale = 1;
Now for drawing your rectangles, this is how you do it:
Paint paint = new Paint();
paint.setColor(Color.GRAY);
paint.setStyle(Style.FILL);
int[] cx = new int[4];
int[] cy = new int[4];
Box box = yourBoxHere;
box.formShape(cx, cy, 1);
Path path = new Path();
path.reset(); // only needed when reusing this path for a new build
path.moveTo(cx[0], cy[0]); // used for first point
path.lineTo(cx[1], cy[1]);
path.lineTo(cx[2], cy[2]);
path.lineTo(cx[3], cy[3]);
path.lineTo(cx[0], cy[0]); // repeat the first point
canvas.drawPath(wallpath, paint);
For multitouch rotation listener you should override 2 methods in your Activity or View:
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getId() == MotionEvent.ACTION_UP)
this.points = null;
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
if(event.getPointerCount() >= 2) {
float newPoints[][] = new float[][] {
{event.getX(0), event.getY(0)},
{event.getX(1), event.getY(1)}
};
double angle = angleBetweenTwoPoints(newPoints[0][0], newPoints[0][1], newPoints[1][0], newPoints[1][1]);
if(points != null) {
double difference = angle - initialAngle;
if(Math.abs(difference) > rotationSensibility) {
listener.onGestureListener(GestureListener.ROTATION, Math.toDegrees(difference));
this.initialAngle = angle;
}
} else {
this.initialAngle = angle;
}
this.points = newPoints;
}
}
public static double angleBetweenTwoPoints(double xHead, double yHead, double xTail, double yTail) {
if(xHead == xTail) {
if(yHead > yTail)
return Math.PI/2;
else
return (Math.PI*3)/2;
} else if(yHead == yTail) {
if(xHead > xTail)
return 0;
else
return Math.PI;
} else if(xHead > xTail) {
if(yHead > yTail)
return Math.atan((yHead-yTail)/(xHead-xTail));
else
return Math.PI*2 - Math.atan((yTail-yHead)/(xHead-xTail));
} else {
if(yHead > yTail)
return Math.PI - Math.atan((yHead-yTail)/(xTail-xHead));
else
return Math.PI + Math.atan((yTail-yHead)/(xTail-xHead));
}
}
Sorry, but this answer is getting long, if you have further questions about any of those operations and you want to change the approach of your solution, please ask again and tell me in the comments.
I hope this was helpful.

Draw line following finger without using canvas.path

In this Example, a pre-defined function is drawn to an interactive chart. This is the code used in the Example:
/**
* The simple math function Y = fun(X) to draw on the chart.
* #param x The X value
* #return The Y value
*/
protected static float fun(float x) {
return (float) Math.pow(x, 3) - x / 4;
}
....
private void drawDataSeriesUnclipped(Canvas canvas) {
mSeriesLinesBuffer[0] = mContentRect.left;
mSeriesLinesBuffer[1] = getDrawY(fun(mCurrentViewport.left));
mSeriesLinesBuffer[2] = mSeriesLinesBuffer[0];
mSeriesLinesBuffer[3] = mSeriesLinesBuffer[1];
float x;
for (int i = 1; i <= DRAW_STEPS; i++) {
mSeriesLinesBuffer[i * 4 + 0] = mSeriesLinesBuffer[(i - 1) * 4 + 2];
mSeriesLinesBuffer[i * 4 + 1] = mSeriesLinesBuffer[(i - 1) * 4 + 3];
x = (mCurrentViewport.left + (mCurrentViewport.width() / DRAW_STEPS * i));
mSeriesLinesBuffer[i * 4 + 2] = getDrawX(x);
mSeriesLinesBuffer[i * 4 + 3] = getDrawY(fun(x));
}
canvas.drawLines(mSeriesLinesBuffer, mDataPaint);
}
I now want to modify this code, so that not a pre-defined function gets drawn, but them path the user draws with his finger on the screen.
(I know that I could easily draw a Path following the user's finger and I have tried it before. Although the path gets drawn correctly, it doesn't behave the way I want it to so I have to try this method).
To draw this Path, I tried to save the points the user touched:
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
firstTouchX = event.getX();
firstTouchY = event.getY();
case MotionEvent.ACTION_MOVE:
lastTouchX = event.getX();
lastTouchY = event.getY();
case MotionEvent.ACTION_UP:
lastTouchX = event.getX();
lastTouchY = event.getY();
}
Point lastTouch = new Point();
lastTouch.set((int)lastTouchX, (int)lastTouchY);
pointsList.add(lastTouch);
Then I changed fun, to return the correct y-value of a point if the x-value of it is passed:
protected static float fun(float x) {
float currX = 0;
float currY = 0;
for (int i = 0; i < pointsList.size(); i++) {
Point curr = pointsList.get(i);
currX = curr.x;
currY = curr.y;
}
if (currX == x) {
return currY;
}
I know this is a very long and complicated question, but I really don't know what else to do and I've tried everything but couldn't manage to find a solution, so I would be really grateful if someone could take the time and take a look at my problem.
To summarize my Problem:
- I want to draw a line, following the touch of the users Finger
- I need to do it without a path, but with the method described above

Android multitouch glitches

I've just made a quick system that has two joysticks (one for movement, one for shooting) and they work with multitouch.
However, when you use both at the same time they interfere with each other (You slow down, turn weirdly, etc) and am wondering whether this is an issue with my phone (Nexus One, 2.3.6) or an issue with the code:
public void handleEvent(MotionEvent event) {
final int action = event.getAction();
switch(action & MotionEvent.ACTION_MASK){
case MotionEvent.ACTION_DOWN: {
pointerID = event.getPointerId(0);
int tx = (int) event.getX(event.findPointerIndex(pointerID));
int ty = (int) event.getY(event.findPointerIndex(pointerID));
boolean reset = true;
if(tx >= (x - radius * 2) && (tx <= (x + radius * 2))) {
if(ty >= (y - radius * 2) && (ty <= (y + radius * 2))) {
dx = (tx - x);
dy = (ty - y);
reset = false;
}
}
if(reset) pointerID = -1;
break;
}
case MotionEvent.ACTION_POINTER_DOWN: {
if(pointerID == -1) {
final int pointerIndex = event.getActionIndex();
pointerID = event.getPointerId(pointerIndex);
int tx = (int) event.getX(pointerIndex);
int ty = (int) event.getY(pointerIndex);
if(tx >= (x - radius * 2) && (tx <= (x + radius * 2))) {
if(ty >= (y - radius * 2) && (ty <= (y + radius * 2))) {
dx = (tx - x);
dy = (ty - y);
}
}
}
break;
}
case MotionEvent.ACTION_MOVE: {
if(pointerID != -1) {
final int pointerIndex = event.findPointerIndex(pointerID);
int tx = (int) event.getX(pointerIndex);
int ty = (int) event.getY(pointerIndex);
if(tx >= (x - radius * 2) && (tx <= (x + radius * 2))) {
if(ty >= (y - radius * 2) && (ty <= (y + radius * 2))) {
dx = (tx - x);
dy = (ty - y);
}
}
}
break;
}
case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = event.getActionIndex();
final int id = event.getPointerId(pointerIndex);
if(id == pointerID) {
dy = 0;
dx = 0;
pointerID = -1;
}
break;
}
case MotionEvent.ACTION_UP: {
if(-1 != pointerID) {
dy = 0;
dx = 0;
pointerID = -1;
}
break;
}
}
}
Important notes:
Each joystick is a class, and the handleEvent method is called for each joystick.
pointerID is an int belonging to each joystick
dy and dx are just the distance from the center of the joystick.
What you are missing is that if there are multiple touches happening at the same time, that one MotionEvent contains them all (and if one of the touches is of the type ACTION_MOVE, it also contains a history of that movement).
Use a loop over event.getPointerCount() (if it is >1) as indexes to get ID's for each touchpoint, which you can then use to track the touch and get the touch's x/y/other information.
Now the thing to realise is that the pointerID not only tracks the touch ... but it also can change if a touch point goes away (finishing with an ACTION_UP event); a POINTER_DOWN event will always add that touch with an ID at the end (so if you have two touches it will get the ID 2), but on a POINTER_UP (or POINTER_2_UP if it''s the second touch point), the points with a higher ID change ID by moving down.
So if you have touches with ID 0, 1 and 2, and the second touch (ID 1) goes POINTER_UP, you have to realise that pointerID 2 will change into ID 1. And if you have two touches (0 and 1), if ID 0 goes up, all of the sudden ID 1 becomes ID 0!
The trick is to keep track of this with some global variables (leftJoyStickID and rightJoyStickID) and some code in action_down and action_up. With just two touchpoints, the ternary operator is your friend:
if (IDofActionUpEvent == leftJoyStickID)
{
rightJoyStickID = IDofActionUpEvent == 0 ? 1 : 0;
}

Categories

Resources