processing游戏开发-方形按钮

1思路

游戏中经常需要做按钮, 按钮是有按压和弹出两种状态。当按钮被按下时,按钮会触发某个函数的执行

1.1长方形

长方形是4个角组成,因此四个坐标就可以定位长方形,也就是说new 一个长方形需要2个参数,分别为2个坐标.两个坐标是topleft 和rightdown , 但由于rightdown坐标可以用width height 和topleft进行计算,实际参数就是 x y w h

1.2碰撞

需要检测是否鼠标在方形内, 并且按下

2实现

全局缓存

RectButton_cache ={}

def setup():
    RectButton_cache['last_page'] = RectButton(521, 212, 20, 110, 'last_page')
    RectButton_cache['next_page'] = RectButton(770, 213, 20, 110, 'next_page')

2.1类

class RectButton:
    def __init__(self, x, y, w, h, name):
        '''

        :param x: topleft
        :param y:
        :param name: 名字
        '''
        self.topleft = PVector(x, y)
        self.isClicked = False
        self.button_i = 11
        self.name = name
        self.disable = False
        self.queue = event_queue
        self.height = h
        self.width = w

    def collide_with_point(self, p):
        x, y = p
        if self.topleft.x < x < self.topleft.x + self.width:
            if self.topleft.y < y < self.topleft.y + self.height:
                return True
        return False

    def update_with_mouse(self, mouse_p, mp):
        if self.collide_with_point(mouse_p):
            if mp:
                self.isClicked = True
                self.queue.append(self.name)
                delay(200)
                return True
        return False

    def show(self, rect_fun):
        rect_fun(self.x, self.y, self.width, self.height)

2.2 run

def draw():

        for rect_ in RectButton_cache.values():# 更新状态
            rect_.update_with_mouse((mouseX, mouseY),mousePressed)
            rect_.isClicked = False# 重置
        if 'next_page' in event_queue:# 下一页
            game_state['page_number'] = 2
            event_queue.remove('next_page')# 消费这条消息
        elif 'last_page' in event_queue:# 上一页
            game_state['page_number'] = 1
            event_queue.remove('last_page')# 消费这条消息
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。