Android - Moving an object in circle

2019-06-04 16:09发布

I'm having trouble with something, I need to make an object (Pong paddle) to move only in a circular route along the screen. same thing as if you would have a constant y axis value and it would only move along the x axis as u drag ur finger on it, but to restrict it to a circular route.

any insights? I saw this thing http://www.kirupa.com/developer/mx/circular.htm

and it only helps in figuring out how to move something constantly at a circle (eventhough it's Flash, the idea is the same)

Thanks

2条回答
一夜七次
2楼-- · 2019-06-04 16:28

The points on a circle can be defined by the functions:

x = a + r cos(θ)
y = b + r sin(θ)

Where (a,b) is the center of the circle.

Depending on the speed you desire, you can say that you want a full circle to happen every T seconds. And if t is the time since the animation began:

θ = (360 / T) * (t % T)

You can use these functions to create your own ViewAnimation, OpenGL function, or if you're using canvas, to set the position of the paddle during the onDraw() event.

查看更多
beautiful°
3楼-- · 2019-06-04 16:46

Here is a block of code I use to rotate an imageview by one finger.

private float mCenterX, mCenterY;
private float direction = 0;
private float sX, sY;
private float startDirection=0;
private void touchStart(float x, float y) {
    mCenterX = this.getWidth() / 2;
    mCenterY = this.getHeight() / 2;
    sX = x;
    sY = y;
}

private void touchMove(float x, float y) {
    // this calculate the angle the image rotate
    float angle = (float) angleBetween2Lines(mCenterX, mCenterY, sX, sY, x,
            y);
    direction = (float) Math.toDegrees(angle) * -1 + startDirection;
    this.invalidate();
}

@Override
protected void onDraw(Canvas canvas) {
    canvas.rotate(direction, mCenterX, mCenterY);
    super.onDraw(canvas);
}

@Override
public boolean onTouchEvent(MotionEvent event) {

    float x = event.getX();
    float y = event.getY();
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
         // record the start position of finger
        touchStart(x, y);
        break;
    case MotionEvent.ACTION_MOVE:
         // update image angle
        touchMove(x, y);
        break;
    case MotionEvent.ACTION_UP:
        startDirection = direction;
        break;
    }

    return true;
}

public double angleBetween2Lines(float centerX, float centerY, float x1,
        float y1, float x2, float y2) {
    double angle1 = Math.atan2(y1 - centerY, x1 - centerX);
    double angle2 = Math.atan2(y2 - centerY, x2 - centerX);
    return angle1 - angle2;
}

Hope this help

Edit: Basically, what the above code does is enable user to rotate an image, and the center of the image will not change. angleBetween2Line() is to calculate the degree that finger has moved in a circle whose center is the image's center.

查看更多
登录 后发表回答