Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to refer to an instance from a different class in the current class in Java
    text
    copied!<p>I am working on bounding box collision of a laser colliding with a monster in Java. There is no problem with collision. The problem is the Rectangle object inside the OneEye class is static! </p> <p>Problem 1: This is no problem if one monster was in the game but in my game I will be adding a lot of instances of the Monster class. So my Rectangle object cannot be static if I were to add more than one monster.</p> <p>Problem 2: Note: if Rectangle object is non-static my getter method for Rectangle needs be non-static.</p> <p>But I cannot seem to figure how to fix these two problems.</p> <p>Again, my collision works! It is more of a code design flaw if I were to add different instances of the same class. To sum it all up, how do I refer to an instance from a different class in the current class I am writing code without referring to it in a static context. </p> <p>Here's my code of two classes: Laser class and OneEye Class</p> <pre><code>public class Laser { /* use a bounding box * to test collision detection * */ private Rectangle rect; public void update(long milliseconds) { // surround a bounding box around the laser rect = new Rectangle((int)position.x,(int)position.y,this.getWidth(),this.getHeight()); // collision against the OneEye monster if(rect.intersects(OneEye.getRectangle())) { Game.getInstance().remove(this); } } public class OneEye { /* * use bounding box * for collision * detection */ private static Rectangle rect; public void update(long milliseconds) { // surround a bounding box around the oneEye monster rect = new Rectangle((int)position.x,(int)position.y,this.getWidth(),this.getHeight()); } // can be useful for collision detection public static Rectangle getRectangle() { return rect; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload