游戏

时间:2017-08-25 10:35:42

标签: java oop collision-detection

我正在开发一个简单的Java游戏,我需要进行菱形 - 矩形碰撞检测。我做到了,但我不知道当他触摸菱形时如何阻止玩家。我的solutoin错了,因为当玩家触摸菱形时,他不能再移动了。我希望玩家可以四处移动,当他触碰到他停下来的障碍物时,但是他仍能继续移动。

有人可以帮助我吗?

这是我的Java代码:

玩家类:

public class Player{
    // I move the player with KeyListener
    public int[] xp,yp;
    public boolean collide;
    public boolean stop;

    public Player(int[]xp,int[]yp){
        stop = false;
        this.xp = xp; 
        this.yp = yp;
        collide = false;
    }
    public void show(Graphics2D g2d){
        g2d.setColor(Color.BLUE);
        if(collide){
            g2d.fillPolygon(new Polygon(this.xp,this.yp,4));
        }
        g2d.drawPolygon(new Polygon(this.xp,this.yp,4));
    }
    public void move(int dx, int dy){
        if(!stop){
            for(int i = 0; i < xp.length; i++){
                xp[i] += dx;
                yp[i] += dy;
            }
        }
    }
    public boolean testIntersec(Polygon poly1){
        Area A1 = new Area(new Polygon(this.xp,this.yp,4));
        A1.intersect(new Area(poly1));
        return !A1.isEmpty();
    }
}

Panel类:

public void init(){
    int[] x = {0,50,50,0};
    int[] y = {0,0,50,50};

    int[] x1 = {0,50,25,-25};
    int[] y1 = {0,0,25,25};

    for(int i = 0; i < x.length; i++){
        x[i] += 300;
        y[i] += 300;
    }
    for(int i = 0; i < x.length; i++){
        x1[i] += 600;
        y1[i] += 600;
    }
    player = new Player(x,y);
    other = new Player(x1,y1);
}

// main loop
public void update(){
    player.update();

    if(player.testIntersec(new Polygon(other.xp,other.yp,4))){
        player.collide = true;
        player.stop = true;
    }else{
        player.collide = false;
        player.stop = false;
    }
}

public void paint(Graphics g){
    Graphics2D g2d = (Graphics2D)g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2d.setColor(Color.WHITE);
    g2d.fillRect(0, 0, width, height);

    player.show(g2d);
    other.show(g2d);
}

0 个答案:

没有答案