我正在为 android 做我的第一个游戏。
我想做一件非常简单的事情,那就是有一个背景和一个会在其中“生成”的球。
所以我制作了我的 GameView:
package com.example.newarkanoid;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
public class Tela extends View {
Paint paint;
int x,y;
int lastx,lasty;
Bola bola;
public Tela(Context context, Bola BOLA) {
super(context);
paint = new Paint();
x=0;lastx=0;
y=0;lasty=0;
bola = BOLA;
bola.paint.setColor(Color.BLACK);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
bola.invalidate();
}
public boolean onTouchEvent(MotionEvent event) {
x = (int)event.getX();
y = (int)event.getY();
if(lastx !=x || lasty !=y){
lastx=x;
lasty=y;
bola.x = x;
bola.y = y;
bola.invalidate();
}
return false;
}
}
好吧,上面是我的 MainDisplay,现在我需要一个球:
package com.example.newarkanoid;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class Bola extends View {
Paint paint;
float x,y,raio;
public Bola(Context context, float x, float y, float raio) {
super(context);
this.x = x;
this.y = y;
this.raio = raio;
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(x, y, raio, paint);
}
}
所以,我确实喜欢那样,因为我的老师告诉我,你不必为内部主显示调用 invalidate,你可以只为你的球调用 invalidate,所以我制作了我的球绘图代码,以及它的属性。
因此,正如您在代码中看到的,当我单击触摸屏中的某个位置时,我的球 x 和 y 将更改为单击位置,然后调用 invalidate。
问题是,当我创建我的 mainDisplay 时,球甚至没有出现,所以我想知道,是否有类似上下文问题的东西?为什么我的球没有抽出来?
另外,这是我的 MainActivity:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bola bola = new Bola(this,20,20,5);
Tela t = new Tela(this,bola);
setContentView(t);
}