Not Letting the Character Move Out of the Window

Not letting the character move out of the window

You could avoid sameness relation comparison == for boundary. I use <= or >= for compare boundary.

I do not know about your code and context, but I suppose circleX, circleY has been changed on other method.

If it change variables as like circleX += 20, it can be passed all if-condition. or if it was called too fast by some events on thread environment, we can not trust the value of circleX.

I recommend to compare as following:

if circleX - 16 <= 0:  # Left border
circleX = 16
elif circleY - 16 <= 0: # Top
circleY = 16
elif circleY + 16 >= 500: # Bottom
circleY = 484
elif circleX + 16 >= 500: # Right
circleX = 484
elif circleY - 16 <= 0 and circleX - 16 <= 0: # Top Left corner
circleY = 16
circleX = 16
elif circleY + 16 >= 500 and circleX + 16 >= 500: # Bottom right
circleX = 484
circleY = 484
elif circleY + 16 >= 500 and circleX - 16 <= 0: # Bottom left
circleY = 484
circleX = 16
elif circleY - 16 <= 0 and circleX + 16 >= 500: # Top right
circleX = 484
circleY = 16

and it can be shorten by using less if condition:

if circleX - 16 <= 0:      # Left border
circleX = 16
if circleY - 16 <= 0: # Top Left corner
circleY = 16
elif circleY - 16 <= 0: # Top
circleY = 16
if circleX + 16 >= 500: # Top right
circleX = 484
elif circleY + 16 >= 500: # Bottom
circleY = 484
if circleX - 16 <= 0: # Bottom left
circleX = 16
elif circleX + 16 >= 500: # Right
circleX = 484
if circleY + 16 >= 500: # Bottom right
circleY = 484

BUT, more short code in my personal favorite is:

circleX = min(max(16, circleX), 484)
circleY = min(max(16, circleY), 484)

Restrict move-able character withing screens bounds on a webpage

You're on the right path with your first case statement:

if($('img').position().left>0) {
...
}

but you are checking if the current position is greater than 0 instead of checking if the new position will be greater than 0.

So instead:

if($('img').position().left - 20 > 0) {
...
}

and do the same thing for the top, right, and bottom case statements as well.

One problem you'll run into is if the user holds down the key for an extended period of time the image will move past the screen because the keydown listener will trigger multiple times while the image hasn't caught up to the correct position due the animations. You'll probably want to prevent keydown while the image is moving.

$(document).ready(function(){
alert("This page has loaded!");

//Below is code which hides a paragraph when the button is clicked
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
//let width =Math.max($(document).width(), $(window).width());
//let height=Math.max($(document).height(), $(window).height());
let height=$(window).height();
let width=$(window).width();
//Below is code which allows for the character to move - why not try craft your own version?
$(document).keydown(function(key) {
// document.write(Math.max($(document).height(), $(window).height()));
// document.write(Math.max($(document).width(), $(window).width()));

console.log(parseInt(key.which,10));
switch(parseInt(key.which,10)) {
// Left arrow key pressed
case 37:
if ($('img').position().left - 20 > 0) {
$('img').animate({left: "-=20px"}, 'fast');
}
break;
// Up Arrow Pressed
case 38:
if ($('img').position().top - 20 > 0) {
$('img').animate({top: '-=20px'},'fast');
}
break;
// Right Arrow Pressed
case 39:
if($('img').position().left + $('img').width() + 20 < width) {
$('img').animate({left: '+=20px'},'fast');
}
break;
// Down Arrow Pressed
case 40:
if ($('img').position().top + $('img').height() + 20 < height) {
$('img').animate({top: '+=20px'},'fast');
}
break;
}
});
});

JSFiddle

CSS/React My button moves out of place when minimizing window

That's because you put position:relative in button element. When you minimize Browser, the button moves to the coordinates you put from one of its element having position: relative. (if you didn't put position :relative to its parents, the button moves from the body element.).

This is why the trouble happened and if you wanna control this, you should remove the position value as code below and position the button with display flex options.

 <button className='button' >

player gets stuck after hitting boundary in pygame

A case of a single symbol.

The critical code is this:

 if keys[pygame.K_w]: # Checks if "w" is pressed

playerCurrentImg = playerFrontImg # Changes current image to correct image

if playerY == 250:
if backgroundY < 0:
backgroundY += playerSpeed
if backgroundY >= 0 or playerY > 250:
playerY -= playerSpeed
if playerY <= 0:
playerY = 0

It is meant to be playerY <= 250 and it is also best pratices to use and instead of nested ifs. Your code should look like this.

    if keys[pygame.K_w]: # Checks if "w" is pressed

playerCurrentImg = playerFrontImg # Changes current image to correct image

if playerY <= 250 and backgroundY < 0:
backgroundY += playerSpeed
if backgroundY >= 0 or playerY > 250:
playerY -= playerSpeed
if playerY <= 0:
playerY = 0

PyGame-Character Goes Off Screen

if not character.get_rect() in screen.get_rect():
print("error")

I see what you are trying here. If you want to check if a Rect is inside another one, use contains():

contains()
test if one rectangle is inside another
contains(Rect) -> bool
Returns true when the argument is completely inside the Rect.

If you simply want to stop the movement on the edges on the screen, an easy solution is to use clamp_ip():

clamp_ip()
moves the rectangle inside another, in place
clamp_ip(Rect) -> None
Same as the Rect.clamp() [Returns a new rectangle that is moved to be completely inside the argument Rect. If the rectangle is too large to fit inside, it is centered inside the argument Rect, but its size is not changed.] method, but operates in place.

Here's a simple example where you can't move the black rect outside the screen:

import pygame
pygame.init()
screen=pygame.display.set_mode((400, 400))
screen_rect=screen.get_rect()
player=pygame.Rect(180, 180, 20, 20)
run=True
while run:
for e in pygame.event.get():
if e.type == pygame.QUIT: run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_w]: player.move_ip(0, -1)
if keys[pygame.K_a]: player.move_ip(-1, 0)
if keys[pygame.K_s]: player.move_ip(0, 1)
if keys[pygame.K_d]: player.move_ip(1, 0)
player.clamp_ip(screen_rect) # ensure player is inside screen
screen.fill((255,255,255))
pygame.draw.rect(screen, (0,0,0), player)
pygame.display.flip()

How can I stop a character in pygame from leaving the edge of the screen?

This should work

if pressed[pygame.K_UP] and y > 0: y -= 5
if pressed[pygame.K_DOWN] and y < 600 - 60: y += 5
if pressed[pygame.K_LEFT] and x > 0: x -= 5
if pressed[pygame.K_RIGHT] and x < 800 - 60: x += 5

Where 600 and 800 is the screen size and 60 the size of your rectangle



Related Topics



Leave a reply



Submit