Sawyer05
Sawyer05

Reputation: 1604

Simple Java Collision Detection

I'm designing a simple game where you're to avoid being hit by the AI i've created.

I've been looking up Collision detection and I have a question.

All the info i've looked up seem to involve using quite a bit of code.

I was wondering why can't a simple:

if(AI.xDirection == x || AI.yDirection == x || AI.xDirection == y || AI.yDirection == y){
        System.out.println("Collision");

Be used for this?

As you see I have it set to print to console and it seems to be working for me.

Is there a disadvantage to this?

Upvotes: 1

Views: 517

Answers (3)

Mik378
Mik378

Reputation: 22191

You violate encapsulation with this way of doing.

Prefer defines a custom object named for instance: AIPosition (likely to be immutable) dedicated to encapsulate AI coordinates.

and AIPosition containing the method: boolean doesCollideWith(AIPosition anotherPosition)

AI would contain a delegating method:

public boolean doesCollideWith(AI anotherAi){
    aiPosition.doesCollideWith(anotherAi.getAIPosition());
} 

Your call would be: if(ai1.doesCollideWith(ai2))

Thus, if later coordinates involve a third element (like z), your client codes don't need to change.

Upvotes: 0

yiwei
yiwei

Reputation: 4190

Your code assumes that all the client cares about is whether or not there is a collision. There may be games and other instances where the client wishes to deal with a collision in certain ways in certain situations (for example, I made a program a while ago that bounced a ball back and forth between random obstacles, and depending on which side was hit first, it had to bounce back in that direction).

The list goes on as to what the client wishes to happen after the collision, but if what you want is simply to show a collision, then hey, go for it man.

Upvotes: 1

Jean Logeart
Jean Logeart

Reputation: 53859

Not sure what your code is actually doing, but if it works and is understandable to you, then I do not see why you should change it!

Upvotes: 2

Related Questions