Created classes Target and Bullet. Threw sprites through ImageIcon and Image. How to detect the collision of objects of both classes?
- oneWell, first you need to do so that they do not collide, i.e. at least just moving, especially true for bullets). Well, actually when driving, i.e. change of coordinates - you check on the intersection of hitboxes. - Russtam
- The movement I did, I’m interested in exactly the collision) if (bullet.posX == target.posX & bullet.posY == target.posY) {...} does not fit ( - Vlad
- both the target and the bullet are points? - Russtam
1 answer
In fact, as noted in the commentary all the same, it comes down to finding common coordinates for two entities ... And how to do it is your business ... As a very simple example, you have an x100 / y100 field, participants in the event: objects- diameters of 20 (D1, D2). The coordinates of the centers of participants are known. Well, the test is to determine the length of a vector between two central points and compare the resulting length with the diameter of the objects as the boundary distance. value. Or get a heresy at the exit)) Above described as a code:
boolean isCross = Math.sqrt(Math.pow(Math.abs(d1.x - d2.x),2)+Math.pow(Math.abs(d1.y - d2.y),2))>20.0d; All of the above-mentioned special case that seems to suit you ... In general, the advice for the future is: split up the question into particulars. What exactly do you mean by a collision? What do analysis participants have in common? etc.
This example is only the first simplified step in obtaining information about a certain dynamic system. What is logical the second step is to determine the collision points and then work with the vectors of each of the objects, etc. Well, refactoring the code then ...
PS Carry out a check before step and not after)
- thanks)) I will try)) - Vlad