Android 摆动的球体

导语

首先,看一下效果 
这里写图片描述 
可能各位在别处看到过类似的东西,我在微信的文章末尾看到有个玩意,感觉有意思,就用代码实现一下。这篇文章主要把握写代码的思路展示一下。 
看到上图,我想各位能想到最简单的实现方案就是用动画,切很多图出来,然后就可以轻松实现了。为了不让自己再舒适区里呆的太安逸,就弄点麻烦的:通过计算来实现。文章的末尾会将全部代码贴出,复制可以直接运行。

需要回忆的知识

  1. 重力势能 E = mgh
  2. 动能 E = ½mv²
  3. 在理想状态下,动能和重力式能可以相互转换,且能量守恒

如果不想太注意细节,以上的知识可以忽略

绘制流程

绘制5个带绳子的球

这里写图片描述 
这步非常简单,概括来说就是:

  1. 确定球的圆心坐标O
  2. 画固定长度的线段OA
  3. 以点O为圆心,画固定半径的球(这样就完成了一个带绳的球)
  4. 绘制多个带绳的球

相关代码在文章末尾已经贴出来了(82-124行,代码中有后续的细节处理,需要甄别下相关的代码),这里只是写下思路,不再重复贴代码了

让球旋转

这里写图片描述

静态图为: 
这里写图片描述 
让带绳子的球旋转,实际上就是改变上图的角α;当α越大,偏移的角度越大;当α越小,偏移的角度越小。 
为了让计算简单,先假设一些前提

  1. α的最大值为45°(这里可以自由给值)
  2. 每次刷新屏幕α改变的值的大小一致且为1(也就是调用invalidate()方法)
  3. 一开始α为45°

有了这些前提限制,实际上,每一次绘图我们的已知条件为:

  1. O点的坐标
  2. 大圆的半径 = 绳子的长度 + 小圆的半径
  3. α的值(因为前提中的2和3,绘制的时候是可以知道当前α的角度)

所以,这步的大致流程为:

  1. 根据大圆的圆心O、半径R,当前α的角度,求B点的坐标(跟前一篇类似,通过画弧,再通过PathMeasure.getPosTan()来获得相应点的坐标)
  2. 绘制线段OB
  3. 以B点为圆心,画半径为固定值的小圆

相关代码在文章末尾已经贴出来了(131-224行,代码中有后续的细节处理,需要甄别下相关的代码),这里只是写下思路,不再重复贴代码了 
如果第一步不知道如何去测量B点的坐标,建议先去看下我前两篇的文章 
音量调节 
绘制仪表盘

模拟现实

在上一步中,我们为了简化模型,让α的改变量每次都为1,但是,这与现实不相符。现实情况是这样的:

  1. 球偏移到最高点时,速度很慢,基本上为0
  2. 球偏移到最低点,速度最快

这里写图片描述

文章一开始,我们已经准备好了需要回忆的知识,现在,让我们回到物理学课堂,说一说简单的摆钟模型计算: 
这里写图片描述 
条件:绳子的长为L,球A静止时,竖直方向的夹角为α 
求:当与竖直方向的夹角为β时的角速度 
这里写图片描述

解题步骤

  1. 求总机械能 
    这里写图片描述 
    当球静止时,机械能 = 重力势能 
    这里写图片描述
  2. 一般情况的表示 
    当球运动时,机械能 = 重力势能 + 动能 
    这里写图片描述 
    经过计算可以得到:这里写图片描述 
    又有公式:这里写图片描述 
    所以最终的结果为这里写图片描述

回归到代码中

好了,得出了结论,让我们回到代码中来:

//计算当前的速率
float v = (float) Math.sqrt(2 * 9.8 * L * (Math.cos( β* Math.PI / 180) - cos(α* Math.PI / 180)));
//计算角速度
float w = v / L;
 
 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

说明:这里只是拟合,并没有特别精确。我们认为当前角度到改变后的角度之间的角速度是一致的,都为当前角度所对应的角速度;所以,在当前角度下,改变角度的量为:这里写图片描述 
具体的实现过程在下面代码的243-250行,是不是感觉很简单?

全部代码

上面罗里吧嗦的半天,终于给出来了可以复制的东西 O(∩_∩)O~

/**
 * Created by kevin on 2016/9/2.
 * <p>
 * 需要推敲的地方:
 * 1.并排绘制多个带绳子的球
 * 2.让左右两端的球可以旋转
 * 3.为了模拟现实,需要根据物理学来计算单位时间旋转的角度
 */
public class Pendulum extends View {

    private Paint linePaint;
    private int width;
    private int height;

    private Path linePath;//用来绘制静态部分的Path
    private Path bigCirclePath;//用来测量大圆的Path
    private Path rotateLinePath;//用来绘制动态部分的Path

    private int stroke = 5; //线段的宽度
    private int r = 20;    //圆圈的半径
    private int length = 400; //线的长度
    private int number = 5; //球的个数(奇数,偶数感觉丑就没实现)
    private static int angle = 50;//最大旋转角度

    // 第一个参数表示角度;负数表示左边球旋转的角度,正数表示右边球旋转的角度
    // +angle表示右侧球偏离最大的角度为30度
    // -angle表示左侧球偏离最大的角度为30度
    // 第二个参数表示方向;-1表示从右往左摆动,1表示从左往右摆动
    private float[] degree = new float[]{angle, -1};

    private float t = 30f;//时间;可以用来控制速率,t越小,摆钟越慢;t越大,摆钟越快
    private float cosO;//cosθ,是个固定值
    private float gr2;//2gr,是个固定值
    private int interval = 40;//时间间隔
    private long last;//上次的时间
    private long now ;//当前的时间

    public Pendulum(Context context) {
        super(context);
        initPaint();
        calCosOAnd2gr();
    }

    public Pendulum(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPaint();
        calCosOAnd2gr();
    }

    public Pendulum(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();
        calCosOAnd2gr();
    }

    /**
     * 用来计算cosθ和2gr
     */
    private void calCosOAnd2gr() {
        //这里为了避免cosα-cosθ=0的情况,所以+0.1
        cosO = (float) Math.cos((angle + 0.1f) * Math.PI / 180);
        //2倍的重力加速度乘以半径
        gr2 = (float) (9.8 * r * 2);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(width / 2, height / 2);

        drawPic(canvas);
        rotate(canvas);

    }


    /**
     * 绘制静态图形
     *
     * @param canvas
     */
    private void drawPic(Canvas canvas) {
        if (number < 1) {
            throw new IllegalArgumentException("数量不能小于1");
        }
        int x;
        if (number % 2 == 1) {
            //奇数的情况
            //用来确定最外层的位置,例如:如果number为3,leftNumber为1
            //                          number为5,leftNumber为2
            //                          number为7,leftNumber为3
            int leftNumber = number / 2;

            for (int i = -leftNumber; i <= leftNumber; i++) {
                if (isRight()) {
                    //最右侧在摇摆
                    if (i == leftNumber)
                        continue;
                } else if (!isRight()) {
                    //最左侧的在摇摆
                    if (i == -leftNumber)
                        continue;
                }
                //计算圆心的横坐标x
                x = 2 * r * i;
                if (linePath == null)
                    linePath = new Path();
                linePath.reset();
                //move到圆心(更准确的坐标为(x,-r),圆绘制出来会把部分线段覆盖;这里只是为了方便表示,不再增加多余的点)
                linePath.moveTo(x, 0);
                //画直线到顶点,(顶点离圆心= 线段的长度 + 半径)
                linePath.lineTo(x, -(r + length));
                //绘制直线
                linePaint.setStyle(Paint.Style.FILL_AND_STROKE);
                canvas.drawPath(linePath, linePaint);
                //绘制圆圈,为了不重合,使用FILL,不绘制线的宽度
                linePaint.setStyle(Paint.Style.FILL);
                canvas.drawCircle(x, 0, r, linePaint);
            }
        } else if (number % 2 == 0) {
            //偶数
            throw new IllegalArgumentException("偶数太丑,没有绘制");
        }
    }

    /**
     * 绘制旋转的图形
     *
     * @param canvas
     */
    private void rotate(Canvas canvas) {
        //左侧球运动和右侧球运动是对称的,使用direction(值为+1或-1)来做标记
        int direction;
        if (isRight()) {
            //右侧球运动,+1
            direction = 1;
        } else {
            //左侧球于东,-1
            direction = -1;
        }
        //measure.getPosTan()中不接受负数,这里需要取绝对值
        float nowDegree = Math.abs(degree[0]);

        linePaint.setStyle(Paint.Style.STROKE);
        //确定单侧外层图片的个数
        int pointNumber = number / 2;
        //确定静态圆形的横坐标,与drawPic中的(x = 2 * r * i)相似
        int x = 2 * r * pointNumber * direction;
        //用来确定大圆圆心的坐标,同时也是线段顶点的坐标
        float[] topPoint = new float[]{x, -(r + length)};

        int totalLength = length + r;
        if (bigCirclePath == null)
            bigCirclePath = new Path();
        bigCirclePath.reset();
        //rectF是用来绘制弧形的:以线段的顶点为圆心,length + r为半径画弧形
        RectF rectF = new RectF(topPoint[0] - totalLength, topPoint[1] - totalLength, topPoint[0] + totalLength, topPoint[1] + totalLength);
        //绘制1/4个圆的弧形
        bigCirclePath.addArc(rectF, 90, -90 * direction);

        //用来确定旋转nowDegree时的边界坐标;
        float[] rotatePoint = new float[2];
        PathMeasure measure = new PathMeasure(bigCirclePath, false);
        //此时,rotatePoint的坐标就为我们图中小圆圈圆心的坐标
        measure.getPosTan(measure.getLength() * (nowDegree) / 90, rotatePoint, null);
        //到现在为止,我们已经知道了圆心的坐标以及线段顶点的坐标了。
        //下面,我们就链接这个两个点,并以rotatePoint为圆心画圆

        //画线段
        if (rotateLinePath == null)
            rotateLinePath = new Path();
        rotateLinePath.reset();
        rotateLinePath.moveTo(topPoint[0], topPoint[1]);
        rotateLinePath.lineTo(rotatePoint[0], rotatePoint[1]);
        canvas.drawPath(rotateLinePath, linePaint);
        //画圆
        linePaint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(rotatePoint[0], rotatePoint[1], r, linePaint);

        //显示文字用的,不用理会
//        linePaint.setTextSize(40);
//        canvas.drawText("当前的改变量:" + rotateAngle(), -200, 100, linePaint);

        //degree[1]表示方向,当为1时,表示从左向右运动,那么degree[0]需要不断增加(这是我规定的;当然要修改的话,可以根据情况来修改,估计修改时会晕菜一段时间)
        if (degree[1] == 1) {
            //从总往右,degree增大
            if (degree[0] < angle) {
                //计算需要转动的角度
                float changeAngle = rotateAngle();
                //改变当前角度的值
                degree[0] = degree[0] + changeAngle;
                if (degree[0] >= angle) {
                    //转过头情况的处理:掉头,放到起始位置
                    degree[0] = angle;
                    degree[1] = -1;
                }
                refreshPic();
            }
            //当达到最右侧时,方向翻转
            if (degree[0] >= angle) {
                degree[1] = -1;
            }
        }
        //degree[1]表示方向,当为-1时,表示从右向左运动,那么degree[0]需要不断减小(这是我规定的;当然要修改的话,可以根据情况来修改,估计修改时会晕菜一段时间)
        else if (degree[1] == -1) {
            //从右往左,degree减小
            if (degree[0] > -angle) {
                //计算需要转动的角度
                float changeAngle = rotateAngle();
                //改变当前角度的值
                degree[0] = degree[0] - changeAngle;
                if (degree[0] <= -angle) {
                    //转过头情况的处理:掉头,放到起始位置
                    degree[0] = -angle;
                    degree[1] = 1;
                }
                refreshPic();
            }
            //当达到最左侧时,方向翻转
            if (degree[0] <= -angle) {
                degree[1] = 1;
            }
        }
    }

    private void refreshPic() {
        now = System.currentTimeMillis();
        long i = now - last;
        long post = interval - i;
        postInvalidateDelayed(post);
        if (post < 0) {
//            Log.e("ddd", "p-->" + post);
        }
        last = now;
    }

    /**
     * 计算当前需要转动的角度
     *
     * @return
     */
    private float rotateAngle() {
        //计算当前的速率
        float v = (float) Math.sqrt(gr2 * (Math.cos(Math.abs(degree[0]) * Math.PI / 180) - cosO));
        //计算需要改变的弧度
        float changedAngle = t * v / length;
        if (changedAngle == 0) {
            changedAngle = 0.001f;
        }
        return changedAngle;
    }

    /**
     * 判断是否是右侧的圆球在动
     *
     * @return true-->右侧的圆球在动
     * false-->左侧的圆球在动
     */
    private boolean isRight() {
        boolean flag = false;
        //degree[0]大于0,表示右侧球在动
        //degree[1]小于0,表示左侧球在动
        if (degree[0] > 0) {
            flag = true;
        } else if (degree[0] < 0) {
            flag = false;
        } else if (degree[0] == 0) {
            //如果degree等于0,需要根据方向来判断哪个求在动
            //degree[1]等于-1表示:球是从右往左在运动,此时,球的速度 v-->0,但还是右侧的球在动
            if (degree[1] == -1) {
                flag = true;
            }
            //与上面的情况相反,是左侧的球在动
            else if (degree[1] == 1) {
                flag = false;
            }
        }
        return flag;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
    }

    private void initPaint() {
        last = System.currentTimeMillis();
        //这里不想弄多个Paint,就用一个Paint来替代了,如果有需要,可以增加Paint来绘制指定的图形
        linePaint = new Paint();
        linePaint.setStrokeWidth(stroke);
        linePaint.setAntiAlias(true);
        linePaint.setStyle(Paint.Style.FILL_AND_STROKE);
        linePaint.setColor(0xff4897fe);
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297

结语

用些简单的物理学知识,感觉好奇怪,不过还好,物理学翻译成代码也只有3行而已。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值