不要停止為理想奮鬥 你或許不知道自己最終變成什麼 但比賽的盡頭是看得到的 你會成為IT鐵人
大家安安,我們現在來實作跳跳球的自定義View吧
重要邏輯:
1.畫一個圓球
2.讓他往下墜 (y移動)
3.到底了要往上彈 (偵測到底部邏輯)
4.往右邊移動,造成視覺往右
缺點:沒算拋物線,若做到更好是算掉下來角度,跟回去的角度
ok,來看一下程式碼吧!!!
1.畫圓跟初始化,也可以改成用constroctor傳進來,會變動
也可以傳delay時間跟快慢進來
init() {
drawPaint= Paint()
drawPaint.color=(Color.MAGENTA)
drawPaint.style=Paint.Style.FILL
objectY=0
}
onMeasure,setMeasuredDimension 設置View的寬跟高
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
var mHeight : Int=measureSize(defaultHeight,heightMeasureSpec)
var mWidth : Int=measureSize(defaultWidth,widthMeasureSpec)
setMeasuredDimension(mWidth,mHeight)
viewHeight=mHeight
viewWidth=mWidth
}
設定是否要掉下來或是彈上去
var direction=true
在onDraw畫圓,根據情況跑不同的runnable
跟如果跳出範圍要停下來
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas.drawCircle(objectX.toFloat(),objectY.toFloat(), 25F,drawPaint)
if (objectX>viewWidth){
objectX=0
}
if(!direction){
Log.d("qqqqqqqqwwq","fff")
handler.postDelayed(corunnable, intervalTime.toLong())
}else{
handler.postDelayed(runnable, intervalTime.toLong())
}
}
往上彈的runnable,objectX是有些微往右
private var corunnable= Runnable {
var tempY=objectY-10
objectY=tempY
Log.d("qqqqqqqqwwq",""+objectY)
if (objectY<0){
Log.d("qqqqqqqqwwq","ttt"+objectY)
direction=true
objectX+=15
objectY=0
}
invalidate()
}
往下彈的runnable,objectX是有些微往右
private var runnable= Runnable {
objectY=objectY+10
if (objectY>viewHeight){
direction=false
objectX+=15
}
invalidate()
}
今天大概就是這樣,剩下的明天見OuO