【发布时间】:2017-05-27 22:22:15
【问题描述】:
所以,我有一个不允许移动到屏幕外的 Sprite。我做了一个函数,将播放器放回屏幕,它应该在的位置(我将播放器的原点设置在它的中间,这就是 *0.5 的含义):
if (playerSprite.getPosition().y + playerSprite.getGlobalBounds().height*0.5 > VideoMode::getDesktopMode().height)
playerSprite.setPosition(Vector2f(playerSprite.getPosition().x, VideoMode::getDesktopMode().height - playerSprite.getGlobalBounds().height*0.5));
if (playerSprite.getPosition().x + playerSprite.getGlobalBounds().width*0.5 > VideoMode::getDesktopMode().width)
playerSprite.setPosition(VideoMode::getDesktopMode().width - playerSprite.getGlobalBounds().width*0.5, playerSprite.getPosition().y);
if (playerSprite.getPosition().y - playerSprite.getGlobalBounds().height*0.5 < 0)
playerSprite.setPosition(Vector2f(playerSprite.getPosition().x, playerSprite.getGlobalBounds().height*0.5));
if (playerSprite.getPosition().x - playerSprite.getGlobalBounds().width*0.5 < 0)
playerSprite.setPosition(Vector2f(playerSprite.getGlobalBounds().width*0.5, playerSprite.getPosition().y));
使用这段代码,我的播放器不会在碰到屏幕边缘时停止(当然,当它不垂直时),而是在屏幕边缘平滑滑动。 但是当我尝试对另一个 Sprite 做同样的事情时,比如说一个矩形 Sprite,无论碰撞的角度如何,玩家都会停下来。谁能向我解释这种行为,也许可以建议我如何让它沿着它的边缘滑动? 这将是我已经尝试过的(这里仅用于向上移动,与左、右、下类似):
if (Keyboard::isKeyPressed(Keyboard::W)
sprite.movePlayer('W', speed);
if(playerSprite.getGlobalBounds().intersects(entity.getGlobalBounds()))
sprite.movePlayer('S', speed);
【问题讨论】:
-
无论你撞到哪一边,它是否总是停止你的运动?根据您的第二个代码 sn-p 我希望某些方面会“滑动”而某些方面会“坚持”。问题(或 a 问题)是您的处理顺序很重要。例如,假设您正在向上移动到实体的左侧。如果您在水平移动之前检查垂直移动,您会看到存在碰撞并在检查水平移动之前将垂直移动反转,这将使您粘住。您需要找到一种方法将碰撞检查与产生的校正分离。
-
是的,它会阻止我的移动,无论我撞到哪一边。我明白你的意思,但我不确定这会解决我的问题。