This page has been translated automatically.
Видеоуроки
Интерфейс
Основы
Продвинутый уровень
Подсказки и советы
Основы
Программирование на C#
Рендеринг
Профессиональный уровень (SIM)
Принципы работы
Свойства (properties)
Компонентная Система
Рендер
Физика
Редактор UnigineEditor
Обзор интерфейса
Работа с ассетами
Контроль версий
Настройки и предпочтения
Работа с проектами
Настройка параметров ноды
Setting Up Materials
Настройка свойств
Освещение
Sandworm
Использование инструментов редактора для конкретных задач
Расширение функционала редактора
Встроенные объекты
Ноды (Nodes)
Объекты (Objects)
Эффекты
Декали
Источники света
Geodetics
World-ноды
Звуковые объекты
Объекты поиска пути
Player-ноды
Программирование
Основы
Настройка среды разработки
C++
C#
UnigineScript
UUSL (Unified UNIGINE Shader Language)
Плагины
Форматы файлов
Материалы и шейдеры
Rebuilding the Engine Tools
Интерфейс пользователя (GUI)
Двойная точность координат
API
Animations-Related Classes
Containers
Common Functionality
Controls-Related Classes
Engine-Related Classes
Filesystem Functionality
GUI-Related Classes
Math Functionality
Node-Related Classes
Objects-Related Classes
Networking Functionality
Pathfinding-Related Classes
Physics-Related Classes
Plugins-Related Classes
IG Plugin
CIGIConnector Plugin
Rendering-Related Classes
VR-Related Classes
Работа с контентом
Оптимизация контента
Материалы
Визуальный редактор материалов
Material Nodes Library
Miscellaneous
Input
Math
Matrix
Textures
Art Samples
Учебные материалы

Настройка курсора мыши и его поведения

Customizing Mouse

Customizing MouseПеренастройка мыши

This example shows how to customize the mouse cursor appearance and change default mouse behavior in your application. It will help you to solve the following tasks:В этом примере показано, как настроить внешний вид курсора мыши и изменить поведение мыши по умолчанию в вашем приложении. Это поможет вам решить следующие задачи:

  • Changing the default mouse cursor image.изменение изображения курсора мыши по умолчанию;
  • Toggling mouse cursor's handling modes.переключение режимов работы с курсором мыши;
  • Customizing your application's icon and title.настройка значка и заголовка вашего приложения.

Defining Mouse Behavior
Перенастройка поведения мыши#

The mouse behavior is defined by assigning any of the following modes:Поведение мыши определяется путем назначения любого из следующих режимов:

  • Grab - the mouse is grabbed when clicked (the cursor disappears and camera movement is controlled by the mouse). This mode is set by default.Grab - мышь захватывается при нажатии (курсор исчезает, и движение камеры контролируется мышью). Этот режим установлен по умолчанию.
  • Soft - the mouse cursor disappears after being idle for a short time period.Soft - курсор мыши исчезает после непродолжительного периода бездействия.
  • User - the mouse is not handled by the system (allows input handling by some custom module).User - мышь не обрабатывается системой (позволяет обрабатывать ввод с помощью какого-либо пользовательского модуля).

There are two ways to set the required mouse behavior mode:Существует два способа установить необходимый режим работы мыши:

  • In the Editor, by selecting the corresponding option in the Controls SettingsВ редакторе, выбрав соответствующую опцию в настройках элементов управления.
  • Via code by adding the corresponding line to the logic (world or system logic, components, expressions, etc.)С помощью кода, добавляя соответствующую строку в логику (логика мира или системы, компоненты, выражения и т.д.).
Исходный код (C++)
ControlsApp::setMouseHandle(Input::MOUSE_HANDLE_SOFT);
//or
ControlsApp::setMouseHandle(Input::MOUSE_HANDLE_USER);

Customizing Mouse Cursor
Изменение формы курсора#

You can change the look of the mouse cursor in your application using any square RGBA8 image you want. This can be done by simply adding the following lines to your code (e.g. the world's init() method):Вы можете изменить внешний вид курсора мыши в приложении, используя любое квадратное изображение RGBA8. Это можно сделать, просто добавив следующие строки в свой код (например, используя глобальный метод init()):

Исходный код (C++)
// loading an image for the mouse cursor
ImagePtr mouse_cursor = Image::create("textures/cursor.png");

// resizing the image to make it square
mouse_cursor->resize(mouse_cursor->getWidth(), mouse_cursor->getWidth());
// checking if our image is loaded successfully and has the appropriate format
if (mouse_cursor->isLoaded() && mouse_cursor->getFormat() == Image::FORMAT_RGBA8)
{
	// setting the image for the OS mouse pointer
	Input::setMouseCursorCustom(mouse_cursor);

	// showing the OS mouse pointer
	Input::setMouseCursorSystem(1);
}

// clearing pointer
mouse_cursor.clear();

Here is a sample RGBA8 image (32x32) you can use for your mouse cursor (download it and put it to the data/textures folder of your project):Вот пример изображения RGBA8 (32x32), которое вы можете использовать в качестве курсора мыши (скачайте его и поместите в папку data/textures вашего проекта):

Sample cursor image

Example Code
Пример кода#

Below you'll find the code that performs the following:Ниже вы найдете код, который выполняет следующие действия:

  • Sets a custom icon and title for the application window.устанавливает пользовательский значок и заголовок для окна приложения;
  • Sets a custom mouse cursor.устанавливает пользовательский курсор мыши;
  • Switches between the three handling modes on pressing the ENTER key.переключается между тремя режимами работы при нажатии клавиши ENTER.

Insert the following code into the AppWorldLogic.cpp file.Вставьте следующий код в файл AppWorldLogic.cpp.

Примечание
Unchanged methods of the AppWorldLogic class are not listed here, so leave them as they are.Неизмененные методы класса AppWorldLogic здесь не перечислены, поэтому оставьте их как есть.
Исходный код (C++)
#include "AppWorldLogic.h"
#include "UnigineUserInterface.h"
#include "UnigineGui.h"
#include "UnigineGame.h"

using namespace Unigine;

// auxiliary variables
ControlsPtr controls;
GuiPtr gui;
String handling_mode[3] = { "GRAB", "SOFT", "USER" };

// widgets
WidgetLabelPtr label;
WidgetLabelPtr label2;
WidgetButtonPtr button;

AppWorldLogic::AppWorldLogic()
{
}

AppWorldLogic::~AppWorldLogic()
{
}

int AppWorldLogic::init()
{
	// initializing auxiliary variables
	controls = Game::getPlayer()->getControls();
	gui = Gui::getCurrent();
    EngineWindowPtr MWindow = WindowManager::getMainWindow();
	// setting a custom icon for the application window
	ImagePtr icon = Image::create("textures/cursor.png");
	if (icon->isLoaded() && icon->getFormat() == Image::FORMAT_RGBA8)
		MWindow->setIcon(icon);
	icon.clear();

	// setting a custom title for the application window
	MWindow->setTitle("Custom Window Title");

	// preparing UI: creating 2 labels and a button and adding them to the GUI
	label = WidgetLabel::create(gui);
	label2 = WidgetLabel::create(gui);
	button = WidgetButton::create(gui, "BUTTON");
	label->setPosition(10, 20);
	label2->setPosition(10, 40);
	button->setPosition(10, 80);
	gui->addChild(label, Gui::ALIGN_OVERLAP | Gui::ALIGN_TOP | Gui::ALIGN_LEFT);
	gui->addChild(label2, Gui::ALIGN_OVERLAP | Gui::ALIGN_TOP | Gui::ALIGN_LEFT);
	gui->addChild(button, Gui::ALIGN_OVERLAP | Gui::ALIGN_TOP | Gui::ALIGN_LEFT);

		// loading an image for the mouse cursor
	ImagePtr mouse_cursor = Image::create("textures/cursor.png");

	// resizing the image to make it square
	mouse_cursor->resize(mouse_cursor->getWidth(), mouse_cursor->getWidth());
	// checking if our image is loaded successfully and has the appropriate format
	if (mouse_cursor->isLoaded() && mouse_cursor->getFormat() == Image::FORMAT_RGBA8)
	{
		// setting the image for the OS mouse pointer
		Input::setMouseCursorCustom(mouse_cursor);

		// showing the OS mouse pointer
		Input::setMouseCursorSystem(1);
	}

	// clearing pointer
	mouse_cursor.clear();
		return 1;
}

int AppWorldLogic::update()
{
	// checking for STATE_USE (ENTER key by default) and toggling mouse handling mode
	if (controls->clearState(Controls::STATE_USE) == 1) {
		switch (ControlsApp::getMouseHandle())
		{
		case Input::MOUSE_HANDLE_GRAB:
			// if the mouse is currently grabbed, we disable grabbing and restore GUI interaction
			if (Input::isMouseGrab())
			{
				Input::setMouseGrab(false);
				Gui::getCurrent()->setMouseEnabled(true);
			}
			Input::setMouseHandle(Input::MOUSE_HANDLE_SOFT);
			break;
		case Input::MOUSE_HANDLE_SOFT:
			Input::setMouseHandle(Input::MOUSE_HANDLE_USER);
			break;
		case Input::MOUSE_HANDLE_USER:
			Input::setMouseHandle(Input::MOUSE_HANDLE_GRAB);
			break;
		}
	}

	// updating info on the current cursor position and mouse handling mode 
	label->setText(String::format("\n MOUSE COORDS: %d, %d)", Gui::getCurrent()->getMouseX(), Gui::getCurrent()->getMouseY()));
	label2->setText(String::format("\n MOUSE HANDLE: %s", handling_mode[Input::getMouseHandle()].get()));

	return 1;
}

// ...
int AppWorldLogic::postUpdate()
{
	// ...
	return 1;
}

int AppWorldLogic::updatePhysics()
{
	// ...
	return 1;
}

int AppWorldLogic::shutdown()
{
	// ...
	return 1;
}

int AppWorldLogic::save(const Unigine::StreamPtr &stream)
{
	// ...
	UNIGINE_UNUSED(stream);
	return 1;
}

int AppWorldLogic::restore(const Unigine::StreamPtr &stream)
{
	// ...
	UNIGINE_UNUSED(stream);
	return 1;
}
Последнее обновление: 07.06.2024
Build: ()