簡體   English   中英

Android-在圓圈中移動對象

[英]Android - Moving an object in circle

我在處理某事時遇到麻煩,我需要制作一個對象(乒乓球拍),使其只能沿屏幕沿圓形路徑移動。 就像您將擁有一個恆定的y軸值,並且僅當您在其上拖動手指時,它會沿x軸移動一樣,但是將其限制為圓形路徑。

有什么見解嗎? 我看到了這個東西http://www.kirupa.com/developer/mx/circular.htm

並且僅有助於弄清楚如何連續不斷地移動某些東西(盡管它是Flash,但想法是相同的)

謝謝

圓上的點可以通過以下功能定義:

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

其中(a,b)是圓的中心。

根據您希望的速度,可以說您希望每T秒發生一個完整的圓圈。 如果t是動畫開始以來的時間:

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

您可以使用這些函數來創建自己的ViewAnimation,OpenGL函數,或者如果您使用的是畫布,則可以在onDraw()事件期間設置槳的位置。

這是我用一根手指旋轉imageview的代碼塊。

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;
}

希望這個幫助

編輯:基本上,以上代碼所做的是使用戶能夠旋轉圖像,並且圖像的中心不會改變。 angleBetween2Line()用於計算手指在以圖像中心為中心的圓中移動的程度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM