SFML定义按钮控件

SFML自定义按钮控件

我们在开发游戏的过程中常常会涉及到按钮的设置,但是SFML不能像游戏引擎一样提供按钮控件,为了方便游戏开发,我们自定义一个按钮类,通过实例化这个类来方便地获得一个按钮。

定义按钮类

Button.h

#pragma once

class Button
{
	//将需要用到Button的类定义为友员类,给app赋值
	friend class StartScene;
	friend class GameScene;
	friend class Menu;
public:
	Button():app(NULL),isActive(false),PreBehRel(false) {};
	bool isActive;//按钮是否活跃状态,这个后面会解释
	bool PreBehRel;//松开之前是否按下,这个后面会解释
	void setTextrue(String s);//设置贴图路径
	void setPosition(int x, int y);//位置
	void setScale(float x, float y);//大小
	void show();//显示按钮
	bool onClick(Event& e);//按钮响应
	Sprite s;//精灵
private:
	Texture t;//贴图
	RenderWindow* app;//在app窗口中显示按钮
};

类中方法的实现

Button.cpp

#include "Button.h"

void Button::setTextrue(String s)
{
	this->t.loadFromFile(s);
	this->s.setTexture(this->t);
}

void Button::setPosition(int x, int y)
{
	this->s.setPosition(x, y);
}

void Button::setScale(float x, float y)
{
	this->s.setScale(x, y);
}

bool Button::onClick(Event& e)
{
	if (!isActive) //如果按钮不是活跃状态(不显示),不响应
		return false;
	bool flag = false;
	FloatRect box = s.getGlobalBounds();//获取按钮的有效点击范围
	if (Mouse::getPosition(*app).x >= box.left && Mouse::getPosition(*app).x <= (box.left + box.width) && Mouse::getPosition(*app).y >= box.top && Mouse::getPosition(*app).y <= (box.top + box.height))
	{
		if (e.type == Event::MouseButtonReleased && e.key.code == Mouse::Left && PreBehRel)
		{
			this->PreBehRel = false;//要先按下再松开才返回true,置于为什么要判断先按下,后面会讲
			flag = true;
		}
		else
			flag = false;
		if (e.type == Event::MouseButtonPressed && e.key.code == Mouse::Left)
		{
			this->s.setColor(Color(125, 125, 0, 255));//按钮按下时的颜色和不透明度
			this->PreBehRel = true;
		}
		else
			this->s.setColor(Color(125, 125, 0, 100));//鼠标指着按钮但未按下时的颜色和不透明度
	}
	else
		this->s.setColor(Color(255,255,255, 255));//默认状态的按钮颜色
	return flag;
}

void Button::show()
{
	isActive = true;//若要显示,则为活跃状态
	(*app).draw(s);
}

部分变量的说明

(1)bool isActive:在由于我在判断鼠标是否在按钮里面是用的getGlobalBounds()方法,不管按钮是否被draw,只要设置了贴图精灵,都能获取按钮的响应范围,这就会导致按钮没有显示的情况下我在设置按钮的位置按下也会触发按钮点击事件,这就不合理,所以设置isActive布尔变量来记录按钮是否活跃(被绘制),所以在调用Button的程序里要把isActive重置为false,在绘制按钮时再设为true。
(2)bool PreBehRel:这个是为了防止场景切换时在同一位置两个场景都有按钮的情况下两个按钮的点击都被触发,本来按照sfml的MouseButtonReleased应该是鼠标松开后返回true,也就是说鼠标点击一下只会返回一次Release,但是在实现中发现如果一个按钮被点击后就在同一位置绘制另一个按钮,这回导致两个按钮的MouseButtonReleased都被返回为true,置于为什么会这样我也不知道,所以设置PreBehRel布尔变量来判断鼠标松开前是否被按下,从而避免了这一问题。另外也是防止鼠标在按钮外面按下不放然后移到按钮里面再松开导致触发按钮事件。

如何使用Button

举例代码如下

RenderWindow app;
Button bt;
bt.app=&app;
while(app.isOpen())
{
	Event e;
	while(app.pollEvent(e))
	{
	if(e.type==Event::Closed())
		app.close();
	}
	bt.isActive=false;
	bt.show();
	if(bt.onClick(e))
	{
		cout<<"clicked!";
	}
}
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Create and develop exciting games from start to finish using SFML About This Book Familiarize yourself with the SFML library and explore additional game development techniques Craft, shape, and improve your games with SFML and common game design elements A practical guide that will teach you how to use utilize the SFML library to build your own, fully functional applications Who This Book Is For This book is intended for game development enthusiasts with at least decent knowledge of the C++ programming language and an optional background in game design. What You Will Learn Create and open a window by using SFML Utilize, manage, and apply all of the features and properties of the SFML library Employ some basic game development techniques to make your game tick Build your own code base to make your game more robust and flexible Apply common game development and programming patterns to solve design problems Handle your visual and auditory resources properly Construct a robust system for user input and interfacing Develop and provide networking capabilities to your game In Detail Simple and Fast Multimedia Library (SFML) is a simple interface comprising five modules, namely, the audio, graphics, network, system, and window modules, which help to develop cross-platform media applications. By utilizing the SFML library, you are provided with the ability to craft games quickly and easily, without going through an extensive learning curve. This effectively serves as a confidence booster, as well as a way to delve into the game development process itself, before having to worry about more advanced topics such as “rendering pipelines” or “shaders.” With just an investment of moderate C++ knowledge, this book will guide you all the way through the journey of game development. The book starts by building a clone of the classical snake game where you will learn how to open a window and render a basic sprite, write well-structured code to implement the design of the game, and use the AABB bounding box collision concept. The next game is a simple platformer with enemies, obstacles and a few different stages. Here, we will be creating states that will provide custom application flow and explore the most common yet often overlooked design patterns used in game development. Last but not the least, we will create a small RPG game where we will be using common game design patterns, multiple GUI. elements, advanced graphical features, and sounds and music features. We will also be implementing networking features that will allow other players to join and play together. By the end of the book, you will be an expert in using the SFML library to its full potential. Style and approach An elaborate take on the game development process in a way that compliments the reader's existing knowledge, this book provides plenty of examples and is kind to the uninitiated. Each chapter builds upon the knowledge gained from the previous one and offers clarifications on common issues while still remaining within the scope of its own subject and retaining clarity. Table of Contents Chapter 1: It's Alive! It's Alive! – Setup and First Program Chapter 2: Give It Some Structure – Building the Game Framework Chapter 3: Get Your Hands Dirty – What You Need to Know Chapter 4: Grab That Joystick – Input and Event Management Chapter 5: Can I Pause This? – Application States Chapter 6: Set It in Motion! – Animating and Moving around Your World Chapter 7: Rediscovering Fire – Common Game Design Elements Chapter 8: The More You Know – Common Game Programming Patterns Chapter 9: A Breath of Fresh Air – Entity Component System Continued Chapter 10: Can I Click This? – GUI Fundamentals Chapter 11: Don't Touch the Red Button! – Implementing the GUI Chapter 12: Can You Hear Me Now? – Sound and Music Chapter 13: We Have Contact! – Networking Basics Chapter 14: Come Play with Us! – Multiplayer Subtleties
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值