From 27b0107b7a7d106f7d7d42052e813133b7c04182 Mon Sep 17 00:00:00 2001 From: kn5886348135 <56352848+kn5886348135@users.noreply.github.com> Date: Tue, 22 Nov 2022 17:12:36 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AD=90=E5=BC=B9=E5=92=8C=E5=9D=A6=E5=85=8B?= =?UTF-8?q?=E5=90=84=E8=87=AA=E7=BB=B4=E6=8A=A4Rectangle?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/example/tankbattle/Bullet.java | 15 ++++++++++++--- src/main/java/com/example/tankbattle/Tank.java | 11 ++++++++++- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/example/tankbattle/Bullet.java b/src/main/java/com/example/tankbattle/Bullet.java index e640117..71065c2 100644 --- a/src/main/java/com/example/tankbattle/Bullet.java +++ b/src/main/java/com/example/tankbattle/Bullet.java @@ -7,6 +7,9 @@ public class Bullet { private static final int SPEED = 6; public static int WIDTH = ResourceMgr.bulletD.getWidth(); public static int HEIGHT = ResourceMgr.bulletD.getHeight(); + + private Rectangle rect = new Rectangle(); + private int x, y; private Dir dir; @@ -20,6 +23,11 @@ public class Bullet { this.dir = dir; this.group = group; this.tf = tf; + + rect.x = this.x; + rect.y = this.y; + rect.width = WIDTH; + rect.height = HEIGHT; } public Group getGroup() { @@ -73,14 +81,15 @@ public class Bullet { break; } + rect.x = this.x; + rect.y = this.y; + if (x < 0 || y < 0 || x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT) living = false; } public void collideWith(Tank tank){ if (this.group == tank.getGroup()) return; - Rectangle rect1 = new Rectangle(this.x, this.y, WIDTH, HEIGHT); - Rectangle rect2 = new Rectangle(tank.getX(), tank.getY(), Tank.WIDTH, Tank.HEIGHT); - if (rect1.intersects(rect2)) { + if (this.rect.intersects(tank.rect)) { tank.die(); this.die(); int eX = tank.getX() + Tank.WIDTH / 2 - Explode.WIDTH / 2; diff --git a/src/main/java/com/example/tankbattle/Tank.java b/src/main/java/com/example/tankbattle/Tank.java index aaa80c3..6d83e50 100644 --- a/src/main/java/com/example/tankbattle/Tank.java +++ b/src/main/java/com/example/tankbattle/Tank.java @@ -1,6 +1,6 @@ package com.example.tankbattle; -import java.awt.Graphics; +import java.awt.*; import java.util.Random; public class Tank { @@ -9,6 +9,8 @@ public class Tank { public static int WIDTH = ResourceMgr.GoodTankD.getWidth(); public static int HEIGHT = ResourceMgr.GoodTankD.getHeight(); + Rectangle rect = new Rectangle(); + private Random random = new Random(); private int x,y; @@ -30,6 +32,11 @@ public class Tank { this.dir = dir; this.group = group; this.tf = tf; + + rect.x = this.x; + rect.y = this.y; + rect.width = WIDTH; + rect.height = HEIGHT; } public void fire(){ @@ -81,6 +88,8 @@ public class Tank { break; } + rect.x = this.x; + rect.y = this.y; if (this.group == Group.BAD && random.nextInt(100) > 95) this.fire(); if (this.group == Group.BAD && random.nextInt(100) > 95) {