Java rectangle collision detection confusion

前端 未结 2 1504
清歌不尽
清歌不尽 2020-11-29 11:06

I have made a simple 2D state change game using Bucky\'s slick Java tutorials, I modified this game and now want to set collisions on the map so that my player can not go th

2条回答
  •  悲哀的现实
    2020-11-29 11:09

    if(house.getBounds().contains(player.getX(),player.getY()){//do something}

    as long as your house and your player rectangles are defined in different classes, java will be able to tell the difference

    create a class first that is a base class for dealing with rectangles:

    public class Rectanglebase{
    
    public void getBounds(){//write method}
    
    //write other methods you will need to use for both rectangles here
    
    public Rectanglebase{//default constructor}
    
    }//end class definition
    

    now write classes for the house and player:

    public class House extends Rectanglebase{
    //getBounds() is inherited, so just write stuff to do with the graphics of the house here
    }
    

    when you generate the house in your main code, you can make your own:

    House house = new House();

    then generate the class for the player in a similar way, then construct in in your main code:

    Player player = new Player()

    house and player are different variables, this is how java will tell the difference between your house and player

提交回复
热议问题