如何一次做两个ifs

时间:2015-05-05 18:00:32

标签: java 2d

我有背景图像和英雄图像。在背景技术中,520(x)和260(y)是房子。我不希望我的英雄能够“穿过”房子,但我的方法不起作用。这就是我到目前为止所做的 (我不知道是否有足够的信息):

public void moveRight() {
   if (HeroX < 730) {
       if (HeroX >= 520 && HeroY >= 260) {
           System.out.println("X = " + HeroX + " , Y = " + HeroY);
       }else {
           System.out.println("X = " + HeroX + " , Y = " + HeroY);
           HeroX = HeroX + HeroSpeed;
       }
   } else {
       System.out.println("Da kann ich nicht weiter gehen!");
   }
}

4 个答案:

答案 0 :(得分:0)

房子(我想)是一个长方形或多边形而不是一条线,所以你为什么不简单地使用这些类中的一个代表房子呢?

//import java.awt.*;

//change the type of house to Polygon, if Rectangle doesn't meet
//your requirements
Rectangle house = new Rectangle(/* insert coordinates here*/);
Rectangle hero = new Rectangle(/* coordinates of the hero*/);

if(house.intersects(hero.x , hero.y , hero.width , hero.height))
     System.out.println("Can't pass");
else
     //move

答案 1 :(得分:0)

你应该询问你的英雄+你的英雄移动速度是否在条件

if((HeroX + herospeed)&gt; = 520&amp; HeroY&gt; = 260) 所以你检查他在移动之前不会经过房子

答案 2 :(得分:0)

 public void moveRight() 
 {
      if (HeroX < 730)  //i guess this is the border
      {
          if(HeroX >= 520 && HeroY >= 260) //this is the house at this position the hero should be already inside, so you have to rework this part
          {
               System.out.println("X = " + HeroX + " , Y = " + HeroY);
          }
          else 
          {
               // here should be the error and also a second if when the hero is farther than the house length

               System.out.println("X = " + HeroX + " , Y = " + HeroY);
               HeroX = HeroX + HeroSpeed;
          }
     } 
     else 
     {
          System.out.println("Da kann ich nicht weiter gehen!");
     }
}

答案 3 :(得分:0)

我认为这更好:

public void moveRight() {
   if (HeroX < 730) {
       if (house.intersects(HeroX , HeroY, 38, 55)) {
           System.out.println("X = " + HeroX + " , Y = " + HeroY);
       }else {
           System.out.println("X = " + HeroX + " , Y = " + HeroY);
           HeroX = HeroX + HeroSpeed;
       }
   } else {
       System.out.println("Da kann ich nicht weiter gehen!");
   }
}
public void moveLeft() {
    if (HeroX > 0) {
        if (house.intersects(HeroX, HeroY, 38, 55)){

        }else {
            System.out.println("X = " + HeroX + " , Y = " + HeroY);
            HeroX -= HeroSpeed;
        }
    }else {
        System.out.println("Da kann ich nicht weiter gehen!");
    }
}
public void moveUp() {
    if (HeroY >= 0) {
        if (house.intersects(HeroX, HeroY, 38, 55)){

        }else {
            System.out.println("X = " + HeroX + " , Y = " + HeroY);
            HeroY -= HeroSpeed;
        }
    }
}