简体   繁体   English

播放器可以移出屏幕吗?

[英]Player can move off screen?

So, I'm creating a simple 2D video game. 因此,我正在创建一个简单的2D视频游戏。 I noticed recently that the player can move off the screen, so I added this code: 我最近注意到播放器可以移出屏幕,因此添加了以下代码:

if (newX <= SIZE * TagsCanvas.SCALE) {
            newX = SIZE * TagsCanvas.SCALE;
        } else if (newX >= TagsCanvas.CANVAS_WIDTH - (SIZE * TagsCanvas.SCALE) - getAABB().getRadX()) {
            newX = TagsCanvas.CANVAS_WIDTH - (SIZE * TagsCanvas.SCALE) - getAABB().getRadX();
        }

        if (newY <= SIZE * TagsCanvas.SCALE) {
            newY = SIZE * TagsCanvas.SCALE;
        } else if (newY >= TagsCanvas.CANVAS_HEIGHT - (SIZE * TagsCanvas.SCALE) - getAABB().getRadY()) {
            newY = TagsCanvas.CANVAS_HEIGHT - (SIZE * TagsCanvas.SCALE) - getAABB().getRadY();
        }

TagsCanvas.CANVAS_WIDTH is the width of the canvas object. TagsCanvas.CANVAS_WIDTH是画布对象的宽度。 Height is the height of the canvas object. 高度是画布对象的高度。 Size is the size of the player, and scale is the scale of the game (At the moment it's 2). 大小是玩家的大小,而规模是游戏的规模(目前为2)。 getAABB().getRadX() returns the radius from the center of the player to the edge (The 'player' is a square box). getAABB().getRadX()返回从播放器中心到边缘的半径(“播放器”是一个方形框)。

Now, the x works fine, but the Y part doesn't. 现在,x可以正常工作,但是Y部分不能正常工作。 It'll block the player from moving up off the map (The first statement), but it will let the player go about 20 points too far down. 它会阻止玩家向上移动地图(第一条陈述),但会让玩家向下移动约20点。 Any help would be appreciated! 任何帮助,将不胜感激!

What you can do is have it wraparound by using the Modulo operator (ie remainder after integer division). 您可以做的是使用Modulo运算符将其环绕(即整数除法后的余数)。

Say you want to move 5 units: Have a method: 假设您要移动5个单位:有一个方法:

public void move(int amt){
 pos = (pos + amt) % TagsCanvas.CANVAS_WIDTH.
}

The Modulo operator makes sure that the value will never be equal to or greater than TagsCanvas.CANVAS_WIDTH. 模运算符确保该值永远不会等于或大于TagCanvas.CANVAS_WIDTH。

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

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