[我正在用射击游戏制作游戏,因此在使用click时,它应该向左或向右移动,但是它是在画布上制作的,而onclick侦听器却无法在其上工作,所以有人告诉我获取画布的坐标并在其上使用onclick侦听器它,但他不告诉我该怎么做我的代码
package --------;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
public class Cannon {
float x = -1; // Cannon's center (x,y)
float y = -1;
float stepX = 40;
int lowerX, lowerY, upperX, upperY;
private Paint paint;
private Context mContext;
// Constructor
public Cannon(int color, Context c) {
paint = new Paint();
paint.setColor(color);
mContext = c;
}
public void setBounds(int lx, int ly, int ux, int uy) {
lowerX = lx;
lowerY = ly;
upperX = ux;
upperY = uy;
x = ux/2;
y = uy;
}
public void moveLeft() {
if (x - 30 > 0) {
x -= stepX;
}
}
public void moveRight() {
if (x + 30 < upperX) {
x += stepX;
}
}
public float getPosition() {
return x;
}
public void draw(Canvas canvas) {
canvas.drawLine(x, y -120, x, y, paint);
canvas.drawRect(x - 90, y - 40, x + 90, y, paint);
}
}
如何通过使矩形的坐标向左移动来对此矩形使用onclick侦听器
您已经有一个方法getPosition
,但是它只返回x
位置。创建一个返回x
并返回y
的位置,例如:
public float getCannonX(){
return x;
}
public float getCannonY(){
return y;
}