Reputation: 33
I am trying to move my player by dragging, but I don't want my player to go out of the screen. How can I limit it in a decent way?
void onPanUpdate(DragUpdateDetails details) {
if(game.screenSize.width >= playerRect.right && playerRect.left >= 0
&& game.screenSize.height >= playerRect.bottom && playerRect.top >= 0) {
playerRect = playerRect.translate(details.delta.dx, details.delta.dy);
} else {
playerRect = playerRect.translate(-details.delta.dx*4.2, -details.delta.dy*4.2);
}
}
I came up with this solution but as you know it is not cool. I appriciate any kind help.
Upvotes: 1
Views: 1936
Reputation: 11552
Happy to see another user of our game engine! The delta also has to be taken into consideration in the check. Something like this should work:
void onPanUpdate(DragUpdateDetails details) {
final delta = details.delta;
final size = game.screenSize
double translateX = delta.dx;
double translateY = delta.dy;
// Make sure that the player never goes outside of the screen in the X-axis
if (playerRect.right + delta.dx >= size.width) {
translateX = size.width - playerRect.right;
} else if (playerRect.left + delta.dx <= 0) {
translateX = -playerRect.left;
}
// Make sure that the player never goes outside of the screen in the Y-axis
if (playerRect.bottom + delta.dy >= size.height) {
translateY = size.height - playerRect.bottom;
} else if (playerRect.top + delta.dy <= 0) {
translateY = -playerRect.top;
}
playerRect = playerRect.translate(translateX, translateY);
}
If you have more in-depth questions I suggest that you join our discord too: https://discord.gg/pxrBmy4
Upvotes: 1