简体   繁体   English

简单的Java碰撞检测

[英]Simple Java Collision Detection

I'm designing a simple game where you're to avoid being hit by the AI i've created. 我正在设计一个简单的游戏,你要避免被我创造的AI击中。

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? 这有不利之处吗?

不确定你的代码实际上在做什么,但如果它有效并且你可以理解,那么我不明白你为什么要改变它!

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. 关于客户希望在碰撞后发生什么的清单继续进行,但是如果你想要的只是展示碰撞,那么嘿,那就去吧。

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. 首选定义一个名为AIPosition的自定义对象: AIPosition (可能是不可变的)专用于封装AI坐标。

and AIPosition containing the method: boolean doesCollideWith(AIPosition anotherPosition) AIPosition包含方法: boolean doesCollideWith(AIPosition anotherPosition)

AI would contain a delegating method: AI将包含一个委托方法:

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

Your call would be: if(ai1.doesCollideWith(ai2)) 你的电话会是: if(ai1.doesCollideWith(ai2))

Thus, if later coordinates involve a third element (like z ), your client codes don't need to change. 因此,如果后面的坐标涉及第三个元素(如z ),则不需要更改客户端代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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