我已经做了一些线程,要求过去的冲突帮助并取得了一些进展,我正在制作一个2D Java游戏,屏幕上的播放器随着键盘输入移动,问题出在我的背景上(地图)有很多障碍,目前我的玩家只是直接穿过他们,到目前为止,在这个论坛的用户的帮助下,我在我的代码中得到了这些代码来检测碰撞:
public void changeBuckyPos(float deltaX, float deltaY) {
float newX = buckyPositionX + deltaX;
float newY = buckyPositionY + deltaY;
// check for collisions
Rectangle rectOne = new Rectangle((int)newX, (int)newY, 40, 40);
Rectangle rectTwo = new Rectangle(-100, -143, 70,70);
if (!rectOne.intersects(rectTwo)) {
buckyPositionX = newX;
buckyPositionY = newY;
}
}
当我把这个代码放入我的游戏时,这个代码现在没有错误,但是出现了一个更大的问题,虽然这个代码没有错误,它什么也没做,我的意思是当我进入游戏时有没有碰撞,当两个矩形相交时什么也没发生,有人可以帮我解决这个问题,我已经坚持了很长时间。
谢谢。
答案 0 :(得分:0)
您的游戏逻辑应该类似于(几乎完整的Java Psydocode):
public class Block{
int speedX;
int speedY;
Rectangle rect;
public void update(){
rect.x+=speedX;
rect.y+=speedY;
}
public void draw(/*Graphics g..or somthing*/){
//draw this single object
}
..getters and setters..
}
public class Game{
List<Block> obstacles;
Block myBlock();
......
void update(){
...
myBlock.update();
for(Block ob: obstacles){
if(myBlock.getRect().intersects(ob.getRect())){
processCollision(ob);
}
ob.update();
}
...
}
public void draw(/*Graphics g..or somthing*/){
//background draw logic
myBlock.draw(g);
for(Block ob: obstacles)
ob.draw(g);
}
void processCollision(Rect ob){
..
do whatever you want with ob
..
}
}