不让角色移出窗外 [英] Not letting the character move out of the window

查看:57
本文介绍了不让角色移出窗外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用这种代码:

if circleX - 16 == 0:
    circleX = 16
elif circleY - 16 == 0:
    circleY = 16
elif circleY + 16 == 500:
    circleY = 484
elif circleX + 16 == 500:
    circleX = 484
elif circleY - 16 == 0 and circleX - 16 == 0:
    circleY = 16
    circleX = 16
elif circleY + 16 == 500 and circleX + 16 == 500:
    circleX = 484
    circleY = 484
elif circleY + 16 == 500 and circleX - 16 == 0:
    circleY = 484
    circleX = 16
elif circleY - 16 == 0 and circleX + 16 == 500:
    circleX = 484
    circleY = 16

但它似乎不起作用,我做错了什么?

But it doesn't seem to work, what am i doing wrong?

推荐答案

你可以避免边界的相同关系比较==.我使用 <=>= 作为比较边界.

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

我不知道您的代码和上下文,但我想 circleXcircleY 已在其他方法上更改.

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

如果像circleX += 20那样改变变量,则可以传递所有if-condition.或者如果它被线程环境上的某些事件调用得太快,我们不能相信circleX的值.

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.

我建议进行如下比较:

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

并且可以通过使用 less if 条件来缩短它:

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)

这篇关于不让角色移出窗外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆