简体   繁体   English

Java 2D游戏问题

[英]Java 2D Game Question

I'm creating my first game in Java. 我正在用Java创建我的第一个游戏。 It is a simple 2D top-down shooter game. 这是一个简单的2D自上而下的射击游戏。 I want to have the camera follow my character around, so, using Canvas, how do I make it so the camera follows the character exactly in the center. 我想让摄像机跟随我的角色,因此,如何使用“画布”使摄像机跟随角色恰好在中央。 While the map is moving when I hit the arrow keys. 当地图移动时,我按箭头键。

One possibility for the logic is such: 逻辑的一种可能性是这样的:

  • Create a listener and attach it to your character (either directly or indirectly depending on your design). 创建一个侦听器并将其附加到您的角色上(直接或间接取决于您的设计)。 Listen for character movement, or position changes. 听角色移动或位置变化。
    • Directly meaning that your character class has an addListener method. 直接意味着您的角色类具有addListener方法。
    • Indirectly meaning that your character class posts events to a global event bus, with which the listeners register to receive events of particular types. 间接意味着您的角色类将事件发布到全局事件总线,侦听器向该事件总线注册以接收特定类型的事件。
  • Calculate the camera position based on the character position & center it accordingly. 根据角色位置计算摄像机位置并相应地居中。 This will require a little math! 这需要一点数学运算!

By implementing this using an event system you can easily separate the logic that centers the camera from the logic that moves the character. 通过使用事件系统来实现,您可以轻松地将使摄像机居中的逻辑与移动角色的逻辑分开。 This way you can have the arrow keys move or you can use click to move and the camera logic will be unaffected. 这样,您可以移动箭头键,也可以使用单击来移动,并且相机逻辑将不受影响。

Sorry I cannot provide general help regarding the actual Java 2D and Canvas calls that you might need to make, but I hope that a broad example of how one might go about doing this helps! 抱歉,我无法提供有关您可能需要进行的实际Java 2D和Canvas调用的一般帮助,但是我希望提供一个广泛的示例来帮助您完成此工作!

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

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