2011年3月5日星期六

自由落體方程式

前文章"在畫布(Canvas)上繪畫圖形"以Math.sin()作為例子示範如何在畫布(Canvas)上繪畫圖形. 本文修改一點點, 在畫布上繪畫自由落體方程式(參考: Wikipedia - Equations for a falling body).

自由落體方程式

本實例中, 我們使用公式 d = (gt^2)/2 計算一個自由落體在某一瞬間的下降距離.

修改"在畫布(Canvas)上繪畫圖形"中的MyCanvas.java
package com.AndroidCanvasDraw;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class MyCanvas extends View {

private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
int canvasVerticalCenter;

int initX, initY;
float initV;
final float constG = 9.8f;

public MyCanvas(Context context) {
super(context);
// TODO Auto-generated constructor stub
init();
}

public MyCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
init();
}

public MyCanvas(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
init();
}

private void init(){
paint.setStyle(Paint.Style.FILL);
paint.setStrokeWidth(3);
paint.setColor(Color.WHITE);

initX = 0;
initY = 300;
initV = 0;
}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
prepareProject();

for(int t = 0; t < getWidth(); t++){
//d = g*t*t/2
float scaledDuration = (float)t/20;
float d = constG * scaledDuration * scaledDuration /2;
float h = initY - d;

if (h >= 0f){
project(t, (int)h, canvas);
}else{
break;
}
}
}

void prepareProject(){
canvasVerticalCenter = getHeight();
}

void project(int x, int y, Canvas c){
c.drawPoint(x, canvasVerticalCenter-y, paint);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}

}

沒有留言:

發佈留言