跟随大佬教程继续,图片资源,视频简介有下载链接。
这个文章是看视频教程写的,不算原创。有条件的可以去油管搜索
RyiSnow
,是一个游戏开发视频制作up主,讲解的非常基础,可以边看边实践,增加对Java SDK中游戏相关API的认识,能学到好多东西。
上一次实现了,一个游戏窗口,窗口添加了一个矩形方块,按w,s,a,d键,可以控制矩形移动;这一次将矩形改为一个player类,控制玩家移动。
添加玩家类
package entity;
public class Player extends Entity {
GamePanel gp;
KeyHandler keyH;
public Player(GamePanel gp, KeyHandler keyH) {
this.gp = gp;
this.keyH = keyH;
setDefaultValues();
getPlayerImage();
direction = "down";
}
public void setDefaultValues() {
x = 100;
y = 100;
speed = 4;
}
public void getPlayerImage() {
try {
up1 = ImageIO.read(getClass().getResourceAsStream("/player/boy_up_1.png"));
up2 = ImageIO.read(getClass().getResourceAsStream("/player/boy_up_2.png"));
down1 = ImageIO.read(getClass().getResourceAsStream("/player/boy_down_1.png"));
down2 = ImageIO.read(getClass().getResourceAsStream("/player/boy_down_2.png"));
left1 = ImageIO.read(getClass().getResourceAsStream("/player/boy_left_1.png"));
left2 = ImageIO.read(getClass().getResourceAsStream("/player/boy_left_2.png"));
right1 = ImageIO.read(getClass().getResourceAsStream("/player/boy_right_1.png"));
right2 = ImageIO.read(getClass().getResourceAsStream("/player/boy_right_2.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void update() {
if (keyH.upPressed || keyH.downPressed || keyH.leftPressed || keyH.rightPressed) {
if (keyH.upPressed) {
direction = "up";
y -= speed;
} else if (keyH.downPressed) {
direction = "down";
y += speed;
} else if (keyH.leftPressed) {
direction = "left";
x -= speed;
} else if (keyH.rightPressed) {
direction = "right";
x += speed;
}
spriteCounter++;
if (spriteCounter > 12) {
if (spriteNum == 1) {
spriteNum = 2;
} else if (spriteNum == 2) {
spriteNum = 1;
}
spriteCounter = 0;
}
}
}
public void draw(Graphics2D g2) {
// g2.setColor(Color.WHITE);
// g2.fillRect(x, y, gp.tileSize, gp.tileSize);
BufferedImage image = null;
switch (direction) {
case "up":
if (spriteNum == 1) {
image = up1;
}
if (spriteNum == 2) {
image = up2;
}
break;
case "down":
if (spriteNum == 1) {
image = down1;
}
if (spriteNum == 2) {
image = down2;
}
break;
case "left":
if (spriteNum == 1) {
image = left1;
}
if (spriteNum == 2) {
image = left2;
}
break;
case "right":
if (spriteNum == 1) {
image = right1;
}
if (spriteNum == 2) {
image = right2;
}
break;
}
g2.drawImage(image, x, y, gp.tileSize, gp.tileSize, null);
}
}
玩家添加图片资源、实现动画
按键动画效果
实现地图Background tiles(背景瓷砖或背景瓦片)
地图文件内容
1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1 0 0 0 0 0 2 2 2 2 0 0 0 0 0 1
1 0 0 0 0 0 2 2 2 2 0 0 0 0 0 1
1 0 0 0 0 0 2 2 2 2 0 0 0 0 0 1
1 0 0 0 0 0 2 2 2 2 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
这里是通过文本文件存储数字,不同数字代表不同的瓷砖/瓦片,根据读取到的数字,绘制对应的瓷砖贴图实现的地图效果。1代表墙,2代表草地,3代表水
解析绘制的效果
动画演示
项目代码
参考gitee
https://gitee.com/ximen502/My2DGame
总结
代码运行后,按键开始有些卡顿,原因还没查找。虽然Java不擅长做游戏客户端,但还是能做的。