简体   繁体   中英

Collision detection for separate class instances - Processing Java

I have a class which spawns an enemy, and a class that spawns a player. At the moment they are both 2 circles coming towards each other. I have made a collision detection function for when they crash, but I can't make it work. I have made the function outside the classes and try to call the position variables of each class, but it says I can't make a static reference to a non static field. I have also tried the collision detection in each class which also doesn't work.

class Player {
    int Pos_X;
    int Pos_Y;
    int Speed;

    Player(int x, int y, int speed) {
        this.Pos_X = x;
        this.Pos_Y = y;
        this.Speed = speed;
    }

    void Update() {
        ellipse(Pos_X, Pos_Y, 40, 40);
        Pos_X += Speed;
    }
}

class Enemy {
    int Pos_X;
    int Pos_Y;
    int Speed;

    Enemy(int x, int y, int speed) {
        this.Pos_X = x;
        this.Pos_Y = y;
        this.Speed = speed;
    }

    void Update() {
        ellipse(Pos_X, Pos_Y, 40, 40);
        Pos_X -= Speed;
    }
}

Player Player1;
Enemy Enemy1;
void setup() {
    size (500, 500);
    Player1 = new Player (0, 200, 3);
    Enemy1 = new Enemy (500, 200, 3);
}

void draw() {
    background(200);
    Player1.Update();
    Enemy1.Update();
    if (intersectsBox(Player.Pos_X, Player.Pos_Y)) { 
        ellipse(100, 100, 100, 100);
    }
}

boolean intersectsBox(float X, float Y) {
    if (X > Enemy.Pos_X && X < Enemy.Pos_X + 40) {
        if (Y > Enemy.Pos_Y && Y < Enemy.Pos_Y + 40) {
          return true;
        }
    }
}

To use a variable that's in a class, you have to refer to an instance of that class. In your code, Enemy is a class, and Enemy1 is an instance of that class. So when you try to do this:

if (X > Enemy.Pos_X && X < Enemy.Pos_X + 40) {

Processing gives you an error because you're using the class, not an instance. Processing doesn't know which Enemy you're talking about. Instead, you have to do something like this:

if (X > Enemy1.Pos_X && X < Enemy1.Pos_X + 40) {

Now Processing knows which instance of the Enemy class you're talking about. You might also pass in an instance of Enemy as a parameter to that function, that way you can use it to collide with multiple enemies.

And just a general piece of advice: your code would be much easier to read if you followed standard formatting and naming conventions- indent your code (Processing will do it for you if you press ctrl+t in the editor), and make sure only classes start with an upper-case letter. Methods and variables should start with lower-case letters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM