对不起各位,我不知道标题是否是解释它的最佳方式。我正在使用 libgdx 在 java 中制作 pacman 克隆。我已经在瓷砖上渲染了 map 和碰撞检测。唯一的问题是,无论发生什么情况,吃 bean 人都应该继续移动。当他向右走时,你向下或向上按它被挡住,他就会停下来。我尝试了很多不同的东西,但似乎无法让它正常工作。
这是我的吃 bean 玩家类
package com.psillidev.pacman1;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Rectangle;
public class player {
private static int height = 16;
private static int width = 16;
private int playerX , playerY;
private int direction;
private Texture playerTexture;
private boolean isAlive;
public player(int startX,int startY) {
playerTexture = new Texture(Gdx.files.internal("data/pacman.png"));
playerX = startX;
playerY = startY;
}
public void move(Map map) {
if (direction == 0) {
if (isNoTile(map,direction,getX(),getY())) {
setY(getY() + (int)(Gdx.graphics.getDeltaTime() + 2));
}
}
if (direction ==1) {
if (isNoTile(map,direction,getX(),getY())) {
setX(getX() + (int)(Gdx.graphics.getDeltaTime() + 2));
}
}
if (direction ==2) {
if (isNoTile(map,direction,getX(),getY())) {
setY(getY() - (int)(Gdx.graphics.getDeltaTime() + 2));
}
}
if (direction ==3) {
if (isNoTile(map,direction,getX(),getY())) {
setX(getX() - (int)(Gdx.graphics.getDeltaTime() + 2));
}
}
}
private boolean isNoTile(Map map, int dir, int translated_x, int translated_y) {
System.out.println("X: " + translated_x + " Y: " + translated_y);
for (Rectangle r : map.getBlockedTiles()) {
switch (dir) {
case 0:
Rectangle up = new Rectangle(translated_x,translated_y + 2 , 16, 16);
if (up.overlaps(r)) {
return false;
}
break;
case 1:
Rectangle right = new Rectangle(translated_x+2,translated_y, 16, 16);
if (right.overlaps(r)) {
return false;
}
break;
case 2:
Rectangle down = new Rectangle(translated_x,translated_y - 2, 16, 16);
if (down.overlaps(r)) {
return false;
}
break;
case 3:
Rectangle left = new Rectangle(translated_x-2,translated_y, 16, 16);
if (left.overlaps(r)) {
return false;
}
break;
default:
break;
}
}
return true;
}
public void render(SpriteBatch batch) {
batch.draw(playerTexture, playerX, playerY);
}
public int getX() {
return playerX;
}
public void setX(int x) {
playerX = x;
}
public int getY() {
return playerY;
}
public void setY(int y) {
playerY = y;
}
public int getDirection() {
return direction;
}
public void setDirection(int dir) {
direction = dir;
}
public Rectangle getRect() {
return new Rectangle(playerX,playerY,width,height);
}
}
最佳答案
我无法根据您提供的代码做出回答,但我的建议是您需要对您的 KeyListener
类进行调整。我假设您有一个 KeyListener
正在监听用户按下箭头键。按下某个键时,您是否正在执行类似 Pacman.setDirection()
的操作?
您实际上需要做的是在调用 setDirection()
之前检测方向是否有效。所以你的 KeyListener
代码应该是这样的......
- 判断用户按下的是上、下、左还是右
- 检查游戏网格/ map 以查看基于吃 bean 人当前位置的方向是否有效
- 如果方向有效,调用
setDirection()
。如果不是,则不要调用任何东西,Pacman 将继续当前方向。
关于java - Pacman 克隆,当在无法访问的方向按下按钮时,如何让 pacman 保持移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16804415/