第一篇:一个防御塔+多个野怪(简易版) 第二篇:防御塔随意放置 自定义View,处理事件分发,up,move,down。 第三篇:防御塔随意放置+多组野怪 第四篇:多波野怪 第五篇:杀死野怪获得金币 第六篇:防御塔可升级,增强攻击力,增大射程
先上图片,防御塔放置,需要注意的是1、放置后刷新view会导致防御塔回到起点。2、防御塔一旦放置就无法移动,只能拆除,这才符合塔防的规则。问题会在下篇解决
我这里命名为TowerView4,下面代码为通用继承View后的代码。
/** * author:liuzhitong * date:2022/9/2 * description: */ public class TowerView4 extends View { public TowerView4(Context context) { this(context,null); } public TowerView4(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public TowerView4(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); towerX = w/2; towerY = h/2; radius = towerX; screenWidth = getContext().getResources().getDisplayMetrics().widthPixels; screenHeight = getContext().getResources().getDisplayMetrics().heightPixels; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); }
我们需要知道防御塔的属性,x,y轴,半径(攻击范围)等
public int towerX,towerY;//防御塔坐标 private Paint paint;//防御塔范围画笔 public int radius;//防御塔攻击范围 public int lastX,lastY;//拖拽时down的坐标 private int offsetX; private int offsetY; private int screenWidth;//屏幕宽度 private int screenHeight; private boolean move=true;//是否可移动 private int left; private int top; public TowerView4(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); paint = new Paint(); paint.setColor(0xffFFcAF9); paint.setAntiAlias(true); paint.setStrokeWidth(2f); paint.setStyle(Paint.Style.STROKE); }
开始绘制出来
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(towerX,towerY,radius,paint); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.pao1); canvas.drawBitmap(bitmap,towerX,towerY,paint); }
这里加了一个icon
然后拖拽我们需要在onTouchEvent中,移动很简单,我就直接上代码了
@Override public boolean onTouchEvent(MotionEvent event) { int rawX = (int) event.getX(); int rawY = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = rawX; lastY = rawY; break; case MotionEvent.ACTION_MOVE: offsetX = rawX - lastX; offsetY = rawY - lastY; left = getLeft()+ offsetX; top = getTop()+ offsetY; int right=getRight()+ offsetX; int bottom =getBottom()+ offsetY; //左边距离边框为0 if(getLeft()+ offsetX<=0){ left = 0; right = towerX*2; } if(right >= screenWidth){ right = screenWidth; left =screenWidth - radius*2; } layout(left, top,right,bottom); break; case MotionEvent.ACTION_UP: //确定是拖拽 break; } return isMove(); }
ok,现在就可以拖拽了。
持续书写中........