ВАЖНО!!"!! 11)0)0)нулик!! ФЛЕШ устарел и не используется, учите Panorama
Создание кастомных событий
Вообще речь пойдет не про кнопку, а про обратную связь. Если в первой части мы использовали кнопки для передачи инфы в скрипты (луа), то теперь наоборот: передадим инфу во флеш, для отображения.
Для этого нужно:
[list type=decimal]
[li]Создать файл с кастомными событиями: scripts/custom_events.txt
[/li]
[li]Подписаться на событие в AS3 (экшнскрипте, который флеш)
this.gameAPI.SubscribeToGameEvent("wood_upd", this.UpdateWood);[/li]
[li]Создать функцию UpdateWood, которую мы указали пунктом выше.
Где text1 и wood1 названия элементов "текст", которые прописываются в свойствах.
Фулл код CustomUI.as и myModule2.as:
[/li]
[li]
Закидываем файл в ресурсы. Теперь можно кодить в луа. В init разделе Создадим переменную wood = 1. В каком-нибудь событии пропишите wood = wood + 5 - имитация добычи дерева.
[/li]
[li]Там же вызовем наше событие:
FireGameEvent('Название_события', { переменная_из_тхт = передаваемое_значение}) // переменных может быть много, смотря сколько указали в тхт.
Пример:
FireGameEvent('wood_upd', { wood_amount = wood })
[/li]
[/list]
Ну вот и все. Не стал объяснять очевидные вещи, те, кто решил создать свой UI, что-то да знают в программировании.
Создание кастомных событий
[youtube]https://www.youtube.com/watch?v=oLC2JAf6V-M&feature=youtu.be[/youtube]
Вообще речь пойдет не про кнопку, а про обратную связь. Если в первой части мы использовали кнопки для передачи инфы в скрипты (луа), то теперь наоборот: передадим инфу во флеш, для отображения.
Для этого нужно:
[list type=decimal]
[li]Создать файл с кастомными событиями: scripts/custom_events.txt
// No spaces in event names, max length 32
// All strings are case sensitive
//
// valid data key types are:
// string : a zero terminated string
// bool : unsigned int, 1 bit
// byte : unsigned int, 8 bit
// short : signed int, 16 bit
// long : signed int, 32 bit
// float : float, 32 bit
// uint64 : unsigned int 64 bit
// local : any data, but not networked to clients
//
// following key names are reserved:
// local : if set to 1, event is not networked to clients
// unreliable : networked, but unreliable
// suppress : never fire this event
// time : firing server time
// eventid : holds the event ID
"CustomEvents"
{
"wood_upd"
{
//Задаем переменные, которые будут переданы, и указываем их тип.
// "название" "тип"
"wood" "short"
}
}
// All strings are case sensitive
//
// valid data key types are:
// string : a zero terminated string
// bool : unsigned int, 1 bit
// byte : unsigned int, 8 bit
// short : signed int, 16 bit
// long : signed int, 32 bit
// float : float, 32 bit
// uint64 : unsigned int 64 bit
// local : any data, but not networked to clients
//
// following key names are reserved:
// local : if set to 1, event is not networked to clients
// unreliable : networked, but unreliable
// suppress : never fire this event
// time : firing server time
// eventid : holds the event ID
"CustomEvents"
{
"wood_upd"
{
//Задаем переменные, которые будут переданы, и указываем их тип.
// "название" "тип"
"wood" "short"
}
}
[li]Подписаться на событие в AS3 (экшнскрипте, который флеш)
this.gameAPI.SubscribeToGameEvent("wood_upd", this.UpdateWood);[/li]
[li]Создать функцию UpdateWood, которую мы указали пунктом выше.
function UpdateWood(keys:Object){ // ADD
// keys объект, содержащий переменные из нашего кастом_ивент.тхт
this.wood1.text = String(keys.wood_amount);
// возьмем че-нить из стандартных АПИ https://developer.valvesoftware.com.../Custom_UI/Actionscript_game_engine_reference
var pID:int = globals.Players.GetLocalPlayer(); // Ид игрока
this.text1.text = pID.toString();
}
// keys объект, содержащий переменные из нашего кастом_ивент.тхт
this.wood1.text = String(keys.wood_amount);
// возьмем че-нить из стандартных АПИ https://developer.valvesoftware.com.../Custom_UI/Actionscript_game_engine_reference
var pID:int = globals.Players.GetLocalPlayer(); // Ид игрока
this.text1.text = pID.toString();
}
Фулл код CustomUI.as и myModule2.as:
package {
import flash.display.MovieClip;
//import some stuff from the valve lib
import ValveLib.Globals;
import ValveLib.ResizeManager;
public class CustomUI extends MovieClip{
//these three variables are required by the engine
public var gameAPI:Object;
public var globals:Object;
public var elementName:String;
//constructor, you usually will use onLoaded() instead
public function CustomUI() : void {
}
//this function is called when the UI is loaded
public function onLoaded() : void {
//make this UI visible
visible = true;
//let the client rescale the UI
Globals.instance.resizeManager.AddListener(this);
//this is not needed, but it shows you your UI has loaded (needs 'scaleform_spew 1' in console)
trace("Custom UI loaded!");
this.mod1.setup(this.gameAPI, this.globals); //ADD
}
//this handles the resizes - credits to SinZ
public function onResize(re:ResizeManager) : * {
//calculate the scaling ratio in the X and Y direction and apply it to the state
var resWidth:int = 0;
var resHeight:int = 0;
if (re.IsWidescreen()) {
if (re.Is16by9()) {
//16:9
resWidth = 1600;
resHeight = 900;
} else {
//16:10
resWidth = 1280;
resHeight = 768;
}
} else {
//4:3
resWidth = 1024;
resHeight = 768;
}
var maxStageHeight:int = re.ScreenHeight / re.ScreenWidth * resWidth;
var maxStageWidth:int = re.ScreenWidth / re.ScreenHeight * resHeight;
// Scale hud to screen
this.scaleX = re.ScreenWidth/maxStageWidth;
this.scaleY = re.ScreenHeight/maxStageHeight;
//You will probably want to scale your elements by 1/scale to keep their original resolution
//Elements are aligned to the top left of the screen in the engine, if you have panels that are not, reposition them here.
// calculate by what ratio the stage is scaling
var scaleRatioX:Number = re.ScreenWidth/maxStageWidth;
var scaleRatioY:Number = re.ScreenHeight/maxStageHeight;
//apply scale ratios to stage
this.scaleX = 1;//scaleRatioX;
this.scaleY = 1;//scaleRatioY;
//You will probably want to scale your elements by 1/scale to keep their original resolution
//Elements are aligned to the top left of the screen in the engine, if you have panels that are not, reposition them here.
this.mod1.screenResize(re.ScreenWidth, re.ScreenHeight, 1/scaleRatioX, 1/scaleRatioY);
}
}
}
import flash.display.MovieClip;
//import some stuff from the valve lib
import ValveLib.Globals;
import ValveLib.ResizeManager;
public class CustomUI extends MovieClip{
//these three variables are required by the engine
public var gameAPI:Object;
public var globals:Object;
public var elementName:String;
//constructor, you usually will use onLoaded() instead
public function CustomUI() : void {
}
//this function is called when the UI is loaded
public function onLoaded() : void {
//make this UI visible
visible = true;
//let the client rescale the UI
Globals.instance.resizeManager.AddListener(this);
//this is not needed, but it shows you your UI has loaded (needs 'scaleform_spew 1' in console)
trace("Custom UI loaded!");
this.mod1.setup(this.gameAPI, this.globals); //ADD
}
//this handles the resizes - credits to SinZ
public function onResize(re:ResizeManager) : * {
//calculate the scaling ratio in the X and Y direction and apply it to the state
var resWidth:int = 0;
var resHeight:int = 0;
if (re.IsWidescreen()) {
if (re.Is16by9()) {
//16:9
resWidth = 1600;
resHeight = 900;
} else {
//16:10
resWidth = 1280;
resHeight = 768;
}
} else {
//4:3
resWidth = 1024;
resHeight = 768;
}
var maxStageHeight:int = re.ScreenHeight / re.ScreenWidth * resWidth;
var maxStageWidth:int = re.ScreenWidth / re.ScreenHeight * resHeight;
// Scale hud to screen
this.scaleX = re.ScreenWidth/maxStageWidth;
this.scaleY = re.ScreenHeight/maxStageHeight;
//You will probably want to scale your elements by 1/scale to keep their original resolution
//Elements are aligned to the top left of the screen in the engine, if you have panels that are not, reposition them here.
// calculate by what ratio the stage is scaling
var scaleRatioX:Number = re.ScreenWidth/maxStageWidth;
var scaleRatioY:Number = re.ScreenHeight/maxStageHeight;
//apply scale ratios to stage
this.scaleX = 1;//scaleRatioX;
this.scaleY = 1;//scaleRatioY;
//You will probably want to scale your elements by 1/scale to keep their original resolution
//Elements are aligned to the top left of the screen in the engine, if you have panels that are not, reposition them here.
this.mod1.screenResize(re.ScreenWidth, re.ScreenHeight, 1/scaleRatioX, 1/scaleRatioY);
}
}
}
package {
import flash.display.MovieClip;
public class myModule2 extends MovieClip {
var gameAPI:Object; //ADD
var globals:Object; //ADD
public function myModule2() {
}
public function setup(api:Object, globals:Object) { //ADD
this.gameAPI = api;
this.globals = globals;
this.gameAPI.SubscribeToGameEvent("wood_upd", this.UpdateWood);
}
function UpdateWood(keys:Object){ // ADD
// keys объект, содержащий переменные из нашего кастом_ивент.тхт
this.wood1.text = String(keys.wood_amount);
// возьмем че-нить из стандартных АПИ
var pID:int = globals.Players.GetLocalPlayer();
this.text1.text = pID.toString();
}
public function screenResize(stageW:int, stageH:int, xScale:Number, yScale:Number){
//we set the position of this movieclip to the center of the stage
//remember, the black cross in the center is our center. You control the alignment with this code, you can align it however you like.
this.x = stageW/2;
this.y = stageH/2;
//A small example of aligning to the right bottom corner would be:
/* this.x = StageW - this.width/2;
* this.y = StageH - this.height/2; */
//Now we just set the scale of this element, because these parameters are already the inverse ratios
this.scaleX = 1;//xScale;
this.scaleY = 1;//yScale;
}
}}
import flash.display.MovieClip;
public class myModule2 extends MovieClip {
var gameAPI:Object; //ADD
var globals:Object; //ADD
public function myModule2() {
}
public function setup(api:Object, globals:Object) { //ADD
this.gameAPI = api;
this.globals = globals;
this.gameAPI.SubscribeToGameEvent("wood_upd", this.UpdateWood);
}
function UpdateWood(keys:Object){ // ADD
// keys объект, содержащий переменные из нашего кастом_ивент.тхт
this.wood1.text = String(keys.wood_amount);
// возьмем че-нить из стандартных АПИ
var pID:int = globals.Players.GetLocalPlayer();
this.text1.text = pID.toString();
}
public function screenResize(stageW:int, stageH:int, xScale:Number, yScale:Number){
//we set the position of this movieclip to the center of the stage
//remember, the black cross in the center is our center. You control the alignment with this code, you can align it however you like.
this.x = stageW/2;
this.y = stageH/2;
//A small example of aligning to the right bottom corner would be:
/* this.x = StageW - this.width/2;
* this.y = StageH - this.height/2; */
//Now we just set the scale of this element, because these parameters are already the inverse ratios
this.scaleX = 1;//xScale;
this.scaleY = 1;//yScale;
}
}}
[/li]
[li]
Закидываем файл в ресурсы. Теперь можно кодить в луа. В init разделе Создадим переменную wood = 1. В каком-нибудь событии пропишите wood = wood + 5 - имитация добычи дерева.
[/li]
[li]Там же вызовем наше событие:
FireGameEvent('Название_события', { переменная_из_тхт = передаваемое_значение}) // переменных может быть много, смотря сколько указали в тхт.
Пример:
FireGameEvent('wood_upd', { wood_amount = wood })
[/li]
[/list]
Ну вот и все. Не стал объяснять очевидные вещи, те, кто решил создать свой UI, что-то да знают в программировании.
Последнее редактирование модератором: