两个类之间如何发生碰撞和反应?
我有一个 Dot 类型的数组,它带有一个 Point 和半径,还有一个 Player,它是一个带有 Point 和大小的矩形。
我想创建一个方法,不断测试玩家是否与数组中的任何点接触/碰撞。我应该在哪里编写代码以及需要传入什么参数?
这是一款玩家必须躲避点的游戏。到目前为止我有这样的事情。
for (int i = 0; i < NUM_DOTS; i++) {
if (player.intersects(dotPos[i])) {
gameOver = true;
}
}
I have an array of type Dot which carries a Point and radius and a Player which is a rectangle with a Point and size.
I would to create a method which is constantly testing if the Player touches/collides with any of the dots in the array. Where would i write the code and what do i need to pass in as parameters?
This is for a game where the player must dodge dots. So far i have something like this.
for (int i = 0; i < NUM_DOTS; i++) {
if (player.intersects(dotPos[i])) {
gameOver = true;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您使用什么前端技术?如果是 Swing/AWT,它们提供可以侦听更改的事件侦听器。对于 Web 应用程序,提交/AJAX 操作是可以查找更改的事件。
如果您想要真正通用,则需要创建一个新线程并将侦听器代码放在 run 方法中。
What front end technology are you using? If Swing/AWT, they provide event listeners that can listen for changes. For a web app, the submission/AJAX action is the even that can look for changes.
If you want to be really generic, you would need to create a new Thread and have your listener code in the run method.
如果允许您使用实现
的类java.awt.Shape
接口,那么定义的intersects()
方法之一可能会有所帮助。If you are allowed to use classes that implement the
java.awt.Shape
interface, then one of definedintersects()
methods may be helpful.另外,lerp 听起来可能会有帮助
also, lerp sounds like it may be helpful
在您的应用程序中,您将有一些事件处理程序来检测用户何时移动。根据游戏的性质,您可以在每次用户移动时进行检查。假设您使用了 keyListener,在按键事件处理程序中您可以使用必须确定碰撞的 for 循环。
此外,您可能有一个正在运行的线程来移动点(点移动吗?)。这是另一个可以放置代码来检查冲突的地方。
In your application you will have some event handler to detect when the user moves. Depending on the nature of the game you can do your check every time the user moves. Lets say you have using a keyListener, the in the keypressed event handler you can use the for loop that you have to determine collision.
In addition you may have a thread running that moves the dots (do the dots move?). This is another place where you can place the code to check for collisions.