障碍物五、金币 在此,暂且先不写金币的动态效果。 - package cn.sqc.runday.model;
- import java.awt.Graphics;
- import java.awt.Image;
- import java.io.File;
- import java.io.IOException;
- import java.util.Random;
- import javax.imageio.ImageIO;
- import cn.sqc.runday.view.GameFrame;
- /**
- * @author Huey
- *2020-11-30 下午03:44:51
- *金币障碍物类
- *
- */
- public class Barrs_5 {
- private Image image;//当前显示图片
- public static final int WIDTH = 30;
- public static final int HEIGHT = 30;
- private int x,y;
- private int speed;
- Random random = new Random();
- public Barrs_5() {
- try {
- image = ImageIO.read(new File("Image/"+(random.nextInt(6) + 21) + ".png"));
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- x = GameFrame.WIDTH + 10;
- y = random.nextInt(600);
- speed = 20;
- }
-
- public void step(){
- x -= speed;
- }
-
- public void paintBarrs(Graphics g){
- g.drawImage(image, x, y, WIDTH, HEIGHT, null);
- }
- public boolean outofBounds() {
- return this.x<=-WIDTH;
- }
- public Image getImage() {
- return image;
- }
- public void setImage(Image image) {
- this.image = image;
- }
- public int getX() {
- return x;
- }
- public void setX(int x) {
- this.x = x;
- }
- public int getY() {
- return y;
- }
- public void setY(int y) {
- this.y = y;
- }
- public int getSpeed() {
- return speed;
- }
- public void setSpeed(int speed) {
- this.speed = speed;
- }
- public Random getRandom() {
- return random;
- }
- public void setRandom(Random random) {
- this.random = random;
- }
- public static int getWidth() {
- return WIDTH;
- }
- public static int getHeight() {
- return HEIGHT;
- }
- }
复制代码
4、玩家和障碍物的碰撞逻辑以玩家与导弹的碰撞举例: - for(int i = 0;i<barrs3.length;i++){
- if(person.getX() + Person.WIDTH >= barrs3[i].getX() &&
- person.getX() <= barrs3[i].getX() + Barrs_3.WIDTH &&
- person .getY() +Person.getHeight() >= barrs3[i].getY() &&
- person.getY() <= barrs3[i].getY () + Barrs_3.HEIGHT){
- if(person.getX() + Person.WIDTH <= barrs3[i].getX() + Barrs_3.WIDTH){//玩家的宽度(120px)是比障碍物小的
- //左碰撞
- person.setX(barrs3[i].getX() - Barrs_3.WIDTH);
- }else{
- //右碰撞
- person.setX(barrs3[i].getX()+ Barrs_3.WIDTH );
- }
- }
- }
复制代码
以下动图演示了玩家从右边与障碍物b发生碰撞和从左边碰撞的逻辑,上下碰撞同理。 上下左右碰撞的逻辑代码,在动图下方: 5、暂停、继续逻辑在监听键盘按键的方法中。 代码如下: 此处的 flag 来源于上面程序启动的方法中,不难看出只要按了空格键,就能实现生成、移动、绘制方法的暂停,也就相当于画面的静止、游戏的暂停! 6、结束逻辑
|