Fasendas
Вы хотите отреагировать на этот пост ? Создайте аккаунт всего в несколько кликов или войдите на форум.
Май 2024
ПнВтСрЧтПтСбВс
  12345
6789101112
13141516171819
20212223242526
2728293031  

Календарь Календарь

Последние темы
» Код вертолета
Создание инвентаря (устаревшее) EmptyПт Май 08, 2020 6:18 pm автор Gedifilyte

» Создание точки появления противников (Устаревшее)
Создание инвентаря (устаревшее) EmptyСб Дек 14, 2019 2:34 am автор Gedifilyte

» Создание инвентаря (устаревшее)
Создание инвентаря (устаревшее) EmptyПт Апр 13, 2018 7:43 pm автор Eris

» Программное создание Mesh
Создание инвентаря (устаревшее) EmptyПн Фев 05, 2018 12:05 am автор Eris

» Помогите !!! (вопросы, советы, обсуждения)
Создание инвентаря (устаревшее) EmptyВт Июн 06, 2017 11:39 am автор Zhuravlev Yuri

» Редакторы карт и ресурсов
Создание инвентаря (устаревшее) EmptyСр Май 24, 2017 10:23 pm автор Чумной Доктор

» Создание "Игрового типа" (GameType)
Создание инвентаря (устаревшее) EmptyСр Апр 05, 2017 2:19 am автор Filat

» Экспорт из 3ds Max
Создание инвентаря (устаревшее) EmptyСб Мар 11, 2017 12:22 pm автор Uggo

» Создание "Выбор персонажа"
Создание инвентаря (устаревшее) EmptyСб Фев 25, 2017 11:32 am автор Filat

Поиск
 
 

Результаты :
 

 


Rechercher Расширенный поиск

Ключевые слова


Создание инвентаря (устаревшее)

Участников: 3

Перейти вниз

Годный урок?

Создание инвентаря (устаревшее) Vote_lcap50%Создание инвентаря (устаревшее) Vote_rcap 50% 
[ 1 ]
Создание инвентаря (устаревшее) Vote_lcap0%Создание инвентаря (устаревшее) Vote_rcap 0% 
[ 0 ]
Создание инвентаря (устаревшее) Vote_lcap50%Создание инвентаря (устаревшее) Vote_rcap 50% 
[ 1 ]
 
Всего проголосовало : 2
 
 
Опрос закрыт

Создание инвентаря (устаревшее) Empty Создание инвентаря (устаревшее)

Сообщение автор Admin Ср Дек 21, 2016 4:30 pm

К сожалению ник автора я уже не помню, кроме того, данный урок уже во многом устарел т.к. делался под старую версию НЕО но возможно он кому ни будь пригодится.




В будущем, возможно будет сделан другой урок, более адаптированный по новые версии.



******************************************************************************




Создание инвентаря (часть 1)

Создание внешнего вида.


В этой части будет рассказано, как сделать UI Model инвентаря на NeoAxis своими руками.
Откройте NeoAxis Resource Editor, и там в папке Gui создайте свою папку, щелкнув правой кнопкой мыши по папке Gui.

[Вы должны быть зарегистрированы и подключены, чтобы видеть эту ссылку]


Назовите ее Inventory.

Нам понадобятся 2 текстуры, первая – неактивный слот, вторая – активный слот.

[Вы должны быть зарегистрированы и подключены, чтобы видеть эту ссылку]


Скопируйте эти текстуры в папку NeoAxis/Game/'Bin/Data/Gui/Inventory.


В NeoAxis Resource Editor'е добавьте новый ресурс, щелкнув правой кнопкой мыши по папке Inventory.

[Вы должны быть зарегистрированы и подключены, чтобы видеть эту ссылку]


В открывшемся окне выберите UI Model.

[Вы должны быть зарегистрированы и подключены, чтобы видеть эту ссылку]


Нажмите Continue->Next.

В поле Base UI Model выберите Base TemplatesButton, а в поле Name напишите InventorySlot.

[Вы должны быть зарегистрированы и подключены, чтобы видеть эту ссылку]


Нажмите Next->Finish.

Аналогично создайте новый ресурс, только в поле Base UI Model выберите Data/Gui/Controls/DefaultWindow.gui, а в поле Name напишите Inventory.

Чтобы установить параметры для слота - щелкните два раза по InventorySlot.gui.

В окне Properties, в параметре BackTexture установите текстуру неактивного слота.

[Вы должны быть зарегистрированы и подключены, чтобы видеть эту ссылку]


В параметрах SoundClick (звук при нажатии на слот) и SoundMouseIntoArea (звук при наведении курсора на слот) можете выбрать свои звуки или использовать стандартные Sounds/ButtonClick.ogg и Sounds/ButtonMouseIntoArea.ogg.

Щелкните правой кнопкой по слоту и выберите Create New Control.

[Вы должны быть зарегистрированы и подключены, чтобы видеть эту ссылку]


В поле Base UI Model выберите Base TemplatesControl и нажмите OK.

[Вы должны быть зарегистрированы и подключены, чтобы видеть эту ссылку]


Выделите созданный Control в окне Control Hierarchy.

[Вы должны быть зарегистрированы и подключены, чтобы видеть эту ссылку]


В окне Properties, в поле Name напишите Icon. Сюда будет загружаться иконка предмета.

Подгоните размеры Icon чтобы он находился внутри слота и был чуть меньше самого слота.

Аналогично добавьте TextBox (в нем будет отображаться количество предметов), разместите его в правом нижнем углу слота и в окне Properties в поле CopyTextFromParent установите True.

Аналогично добавьте еще 5 Control но только в поле ParentControlSlot выбирайте поочередно все кроме (No special Slot).

Далее выделите элементы OverControl, PushControl, ActiveControl как показано на рисунке ниже.

[Вы должны быть зарегистрированы и подключены, чтобы видеть эту ссылку]


В параметре BackTexture выберите текстуру активного слота, а для DefaultControl поставьте текстуру неактивного слота.
На этом создание слота завершено. Сохраните его.


Аналогично откройте для редактирования Inventory.gui.

Добавьте в инвентарь 10 ранее созданных слотов Data/Gui/Inventory/InventorySlot.gui и дайте им имена Slot0, … , Slot9. Это будут сами слоты инвентаря.
Добавьте еще 2 слота и назовите их MainWeapon и Pistol. Это слоты, в которых будет отображаться текущее оружие.

Добавьте еще 2 слота и назовите их Drop и Kill. Эти слоты будут использоваться для выбрасывания и уничтожения вещей.

Добавьте Data/Gui/Controls/Word/Wrap/EditBox.gui, назовите его Info, а параметр Enable установите False. В него мы будем выводить информацию о вещи.

Добавьте Data/Gui/Controls/Default/Button.gui, назовите ее Close, а в поле Text введите Закрыть. Это будет кнопка для закрытия инвентаря.

У вас должно получиться примерно это:

[Вы должны быть зарегистрированы и подключены, чтобы видеть эту ссылку]


Последний раз редактировалось: Admin (Чт Дек 22, 2016 12:14 pm), всего редактировалось 1 раз(а)

Admin
Admin

Сообщения : 24
Рейтинг : 2770
Репутация : 0
Дата регистрации : 2016-12-15

https://fasendas.forum2x2.ru

Вернуться к началу Перейти вниз

Создание инвентаря (устаревшее) Empty Re: Создание инвентаря (устаревшее)

Сообщение автор Admin Ср Дек 21, 2016 4:51 pm

Создания инвентаря. (часть 2).


Создание кода.

В этой части я расскажу, как сделать свой класс инвентаря на NeoAxis. Нам понадобятся еще 2 текстуры, первая - иконка выброса вещи, вторая - иконка уничтожения вещи.

Я возьму свой готовый класс и буду комментировать фрагменты кода. В классе будут использоваться объекты созданные в предыдущей статье.




Код:
//Подключение необходимых библиотек


using System.Collections.Generic;


using Engine;


using Engine.Renderer;


using Engine.MathEx;


using Engine.UISystem;


using Engine.EntitySystem;


using Engine.FileSystem;





namespace GameEntities


{


//Класс инвентаря


public class EInventory : EControl


{


///////////////////////////////////////////





//Класс слота инвентаря


public class ESlot


{


//Ссылка на кнопку слота


EButton button;


public EButton Button


{


get { return button; }


set { button = value; }


}


//Ссылка на иконку слота


EControl icon;


public EControl Icon


{


get { return icon; }


set { icon = value; }


}


//Индекс предмета


int index = -1;


public int Index


{


get { return index; }


set { index = value; }


}


//Тип предмета


ItemSlot slot = ItemSlot.None;


public ItemSlot Slot


{


get { return slot; }


set { slot = value; }


}


//True - если слот свободен, иначе - false


public bool IsFree


{


get { return index == -1; }


}


//Конструктор поумолчанию


public ESlot()


{


}


//Конструктор с параметром


public ESlot( EButton Button )


{


button = Button;


if( button != null )


{


icon = button.Controls[ "Icon" ];


}


}


//Конструктор с параметрами


public ESlot( EButton Button, EControl Icon )


{


button = Button;


icon = Icon;


}


//Функция копирует данные из объекта Source в текущий


public void Copy( ESlot Source )


{


index = Source.Index;


slot = Source.Slot;


icon.BackTexture = Source.Icon.BackTexture;


button.Text = Source.Button.Text;


}


//Функция меняет местами данные объектов Slot1 и Slot2


public static void Swap( ESlot Slot1, ESlot Slot2 )


{


ESlot Temp = new ESlot( new EButton(), new EControl() );


Temp.Copy( Slot1 );


Slot1.Copy( Slot2 );


Slot2.Copy( Temp );


}


}





///////////////////////////////////////////





//Список слотов


List Slots = new List();


//Ссылка на персонажа игрока


PlayerCharacter PlayerChar;


//Ссылка на инвентарь


EControl Inventory;


//Ссылка на окно для вывода информации об объекте


EEditBox Info;


//Ссылка на слот с основным оружием


ESlot MainWeapon;


//Ссылка на слот с пистолетом


ESlot Pistol;


//Ссылка на слот для выбрасывания предмета


ESlot Drop;


//Ссылка на слот для уничтожения предмета


ESlot Kill;


//Ссылка на слот над которым сейчас курсор


ESlot MouseOverSlot;


//Ссылка на перетаскиваемый слот


ESlot DragItem;


//Время первого щелчка по слоту


float FirstClickTime;


//Время ожидания второго щелчка по слоту


float Delay = 0.3f;


//Функция вызываемая при открытии инвентаря


protected override void OnAttach()


{


base.OnAttach();


//Создание окна инвентаря и получение ссылки на него


Inventory = ControlDeclarationManager.Instance.CreateControl( "GUIInventoryInventory.gui" );


Inventory.MouseCover = true;


Controls.Add( Inventory );


//Получение ссылки на персонажа игрока


PlayerChar = GetPlayerUnit() as PlayerCharacter;


//Получение ссылок на слоты основного оружия и пистолета


MainWeapon = new ESlot( (EButton)Inventory.Controls[ "MainWeapon" ] );


Pistol = new ESlot( (EButton)Inventory.Controls[ "Pistol" ] );


//Получение ссылок на слоты выброса и уничтожения предмета


Drop = new ESlot( (EButton)Inventory.Controls[ "Drop" ] );


Kill = new ESlot( (EButton)Inventory.Controls[ "Kill" ] );


//Загрузка иконок слотов выброса и уничтожения


Drop.Icon.BackTexture = TextureManager.Instance.Load( "GuiInventoryDrop.png", Texture.Type.Type2D, 0 );


Kill.Icon.BackTexture = TextureManager.Instance.Load( "GuiInventoryKill.png", Texture.Type.Type2D, 0 );


//Получение ссылки на окно информации


Info = (EEditBox)Inventory.Controls[ "Info" ];


//Заполнение списка слотов


for( int i = 0; i < PlayerChar.InventorySize; i++ )


{


Slots.Add( new ESlot( (EButton)Inventory.Controls[ "Slot" + i ] ) );


}


//Просмотр списка-инвентаря персонажа


for( int i = 0; i < PlayerChar.Items.Count; i++ )


{


//Если слот не пустой


if( PlayerChar.Items[ i ].Index != -1 )


{


//Получение ссылки на данный слот


ESlot Slot = GetSlot( "Slot" + i );


if( Slot != null )


{


string FileName = PlayerChar.Type.Items[ PlayerChar.Items[ i ].Index ].Icon;


//Если есть иконка для данного предмета


if( FileExists( FileName ) )


{


//Заполнение данных слота


Slot.Icon.BackTexture = TextureManager.Instance.Load( FileName, Texture.Type.Type2D, 0 );


Slot.Index = PlayerChar.Items[ i ].Index;


Slot.Slot = PlayerChar.Type.Items[ Slot.Index ].Slot;


if( PlayerChar.Items[ i ].Count > 1 )


{


Slot.Button.Text = PlayerChar.Items[ i ].Count.ToString();


}


}


}


}


}


//Если слот с основным оружием не пустой


if( PlayerChar.MainWeapon.Index != -1 )


{


string FileName = PlayerChar.Type.Items[ PlayerChar.MainWeapon.Index ].Icon;


//Если есть иконка данного предмета


if( FileExists( FileName ) )


{


//Заполнение данных слота


MainWeapon.Icon.BackTexture = TextureManager.Instance.Load( FileName, Texture.Type.Type2D, 0 );


MainWeapon.Index = PlayerChar.MainWeapon.Index;


MainWeapon.Slot = PlayerChar.Type.Items[ MainWeapon.Index ].Slot;


}


}


//Если слот с пистолетом не пустой


if( PlayerChar.Pistol.Index != -1 )


{


string FileName = PlayerChar.Type.Items[ PlayerChar.Pistol.Index ].Icon;


//Если есть иконка данного предмета


if( FileExists( FileName ) )


{


//Заполнение данных слота


Pistol.Icon.BackTexture = TextureManager.Instance.Load( FileName, Texture.Type.Type2D, 0 );


Pistol.Index = PlayerChar.Pistol.Index;


Pistol.Slot = PlayerChar.Type.Items[ Pistol.Index ].Slot;


}


}


//Создание функции-обработчика нажатия на слоты


for( int i = 0; i < PlayerChar.InventorySize; i++ )


{


Slots[ i ].Button.Click += new EButton.ClickDelegate( Slot_Click );


}


MainWeapon.Button.Click += new EButton.ClickDelegate( Slot_Click );


Pistol.Button.Click += new EButton.ClickDelegate( Slot_Click );


Drop.Button.Click += new EButton.ClickDelegate( Slot_Click );


Kill.Button.Click += new EButton.ClickDelegate( Slot_Click );


//Функция обработчик нажатия на кнопку "Закрыть"


( (EButton)Inventory.Controls[ "Close" ] ).Click += delegate( EButton sender )


{


//Если инвентарь открыт


if( PlayerChar.Inventory != null )


{


//Удаление окна и продолжение игрового процесса


PlayerChar.Inventory.SetShouldDetach();


PlayerChar.Inventory = null;





EntitySystemWorld.Instance.Simulation = true;


EngineApp.Instance.MouseRelativeMode = true;


}


};


}


//Функция периодично вызываемая (период зависит от FPS)


protected override void OnTick( float Delta )


{


base.OnTick( Delta );


//Если курсор находится над слотом


if( MouseOverSlot != null )


{


//В информационном окне выводится соответствующая информация


Info.Text = "";


if( MouseOverSlot == Kill )


{


Info.Text += "Уничтожить";


}


else if( MouseOverSlot == Drop )


{


Info.Text += "Выбросить";


}


else if( MouseOverSlot == MainWeapon )


{


Info.Text += "Основное оружиеn-----n";


}


else if( MouseOverSlot == Pistol )


{


Info.Text += "Пистолетn-----n";


}


if( MouseOverSlot.Index != -1 )


{


if( MouseOverSlot.Slot == ItemSlot.MainWeapon && MainWeapon.Index != -1 && MouseOverSlot != MainWeapon )


{


Info.Text += "Снаряжено: " + PlayerChar.Type.Items[ MainWeapon.Index ].Hint + "n-----n";


}


else if( MouseOverSlot.Slot == ItemSlot.Pistol && Pistol.Index != -1 && MouseOverSlot != Pistol )


{


Info.Text += "Снаряжено: " + PlayerChar.Type.Items[ Pistol.Index ].Hint + "n-----n";


}


Info.Text += PlayerChar.Type.Items[ MouseOverSlot.Index ].Hint;


}


}


else


{


Info.Text = "";


}


}


//Функция вызываемая при движении курсора


protected override bool OnMouseMove()


{


//Проверяются все слоты и если курсор над какимто слотом,


//то сохраняется ссылка на этот слот


MouseOverSlot = null;


for( int i = 0; i < PlayerChar.InventorySize; i++ )


{


if( IsMouseOverSlot( Slots[ i ] ) )


{


MouseOverSlot = Slots[ i ];


break;


}


}


if( MouseOverSlot == null )


{


if( IsMouseOverSlot( MainWeapon ) )


{


MouseOverSlot = MainWeapon;


}


else if( IsMouseOverSlot( Pistol ) )


{


MouseOverSlot = Pistol;


}


else if( IsMouseOverSlot( Kill ) )


{


MouseOverSlot = Kill;


}


else if( IsMouseOverSlot( Drop ) )


{


MouseOverSlot = Drop;


}


}





return base.OnMouseMove();


}


//Возвращает ссылку на персонажа игрока


Unit GetPlayerUnit()


{


if( PlayerIntellect.Instance == null )


{


return null;


}


return PlayerIntellect.Instance.ControlledObject;


}


//Возвращает координаты курсора


Vec2 GetMousePos()


{


//Координаты переводятся в удобный формат


return new Vec2( Inventory.MousePosition.X * Inventory.Size.Value.X, Inventory.MousePosition.Y * Inventory.Size.Value.Y );


}


//Возвращает ссылку на слот по его названию


ESlot GetSlot( string Name )


{


//Проверяются все слоты и сравнивается имя кнопки слота


for( int i = 0; i < PlayerChar.InventorySize; i++ )


{


if( Name == Slots[ i ].Button.Name )


{


return Slots[ i ];


}


}


if( Name == MainWeapon.Button.Name )


{


return MainWeapon;


}


if( Name == Pistol.Button.Name )


{


return Pistol;


}


if( Name == Drop.Button.Name )


{


return Drop;


}


if( Name == Kill.Button.Name )


{


return Kill;


}





return null;


}


//Возвращает номер слота по сслыке на слот


int GetSlotIndex( ESlot Slot )


{


for( int i = 0; i < PlayerChar.InventorySize; i++ )


{


if( Slot == Slots[ i ] )


{


return i;


}


}


return -1;


}


//Возвращает true - если файл существует, иначе - false


bool FileExists( string FileName )


{


if( !string.IsNullOrEmpty( FileName ) )


{


return VirtualFile.Exists( FileName );


}





return false;


}


//Возвращает true - если курсор находится над слотом, иначе - false


bool IsMouseOverSlot( ESlot Slot )


{


Vec2 Mouse = GetMousePos();


return Mouse.X >= Slot.Button.Position.Value.X &&


Mouse.X <= Slot.Button.Position.Value.X + Slot.Button.Size.Value.X &&


Mouse.Y >= Slot.Button.Position.Value.Y &&


Mouse.Y <= Slot.Button.Position.Value.Y + Slot.Button.Size.Value.Y;


}


//Меняет местами Slot1 и Slot2 если это позволяет логика игры


void Swap( ESlot Slot1, ESlot Slot2 )


{


if( Slot1 == Slot2 )


{


return;


}


if( Slot1 == MainWeapon )


{


PlayerCharacter.InventoryItem.Swap( PlayerChar.MainWeapon, PlayerChar.Items[ GetSlotIndex( Slot2 ) ] );


}


else if( Slot1 == Pistol )


{


PlayerCharacter.InventoryItem.Swap( PlayerChar.Pistol, PlayerChar.Items[ GetSlotIndex( Slot2 ) ] );


}


else if( Slot2 == MainWeapon )


{


PlayerCharacter.InventoryItem.Swap( PlayerChar.MainWeapon, PlayerChar.Items[ GetSlotIndex( Slot1 ) ] );


}


else if( Slot2 == Pistol )


{


PlayerCharacter.InventoryItem.Swap( PlayerChar.Pistol, PlayerChar.Items[ GetSlotIndex( Slot1 ) ] );


}


else


{


PlayerCharacter.InventoryItem.Swap( PlayerChar.Items[ GetSlotIndex( Slot1 ) ], PlayerChar.Items[ GetSlotIndex( Slot2 ) ] );


}


ESlot.Swap( Slot1, Slot2 );


}


//Функция уничтожения предмета


void KillItem( ESlot Slot )


{


//Если выбрасывается предмет из слота основного оружия


if( Slot == MainWeapon )


{


if( PlayerChar.ActiveSlot == ItemSlot.MainWeapon )


{


PlayerChar.SetActiveWeapon( -1 );


}


PlayerChar.ActiveMainWeapon = -1;


PlayerChar.MainWeapon.Index = -1;


}


//Если выбрасывается предмет из слота пистолета


else if( Slot == Pistol )


{


if( PlayerChar.ActiveSlot == ItemSlot.Pistol )


{


PlayerChar.SetActiveWeapon( -1 );


}


PlayerChar.ActivePistol = -1;


PlayerChar.Pistol.Index = -1;


}


//Если выбрасывается предмет из обычного слота


else


{


PlayerChar.Items[ GetSlotIndex( Slot ) ].Index = -1;


}


Slot.Index = -1;


Slot.Icon.BackTexture = null;


}


//Функция выброса предмета


void DropItem( ESlot Slot )


{


//Создание предмета перед игроком


Item DropedItem = (Item)Entities.Instance.Create( PlayerChar.Type.Items[ Slot.Index ].ItemType, PlayerChar.Parent );


DropedItem.Position = new Vec3( PlayerChar.Position.X + PlayerChar.Rotation.ToMat3().Item0.X * 1.5f,


PlayerChar.Position.Y + PlayerChar.Rotation.ToMat3().Item0.Y * 1.5f,


PlayerChar.Position.Z );


DropedItem.PostCreate();





BulletItem Bullets = DropedItem as BulletItem;


//Если выбрасываемый предмет может хранить патроны


if( Bullets != null )


{


//Если выбрасывается оружие


if( Slot.Slot != ItemSlot.Ammo )


{


Bullets.Type.BulletCount = 0;


Bullets.Type.BulletCount2 = 0;


}


//Если выбрасываются патроны


else


{


Bullets.Type.BulletCount = PlayerChar.Items[ GetSlotIndex( Slot ) ].Count;





int gunIndex = PlayerChar.GetBulletGun( Slot.Index );


if( gunIndex != -1 )


{


PlayerChar.Type.Items[ gunIndex ].NormalBulletCount = 0;





if( PlayerChar.ActiveWeapon != null && PlayerChar.ActiveWeapon.Type == PlayerChar.Type.Items[ gunIndex ].Type )


{


Gun gun = PlayerChar.ActiveWeapon as Gun;


if( gun != null )


{


gun.NormalMode.BulletCount = 0;


gun.NormalMode.BulletMagazineCount = 0;


}


}


}





PlayerChar.Items[ GetSlotIndex( Slot ) ].Count = 0;


}


}


//Уничтожение предмета в инвентаре


KillItem( Slot );


}


//Восстановление жизней у игрока, при использовании аптечки


void Heal( ESlot Slot )


{


HealthItemType HealthItem = PlayerChar.Type.Items[ Slot.Index ].Type as HealthItemType;


if( HealthItem != null )


{


PlayerChar.SoundPlay3D( HealthItem.SoundUse, .5f, true );





float lifeMax = PlayerChar.Type.LifeMax;





if( PlayerChar.Life < lifeMax )


{


float life = PlayerChar.Life + HealthItem.Health;


if( life > lifeMax )


life = lifeMax;





PlayerChar.Life = life;


}


}


}


//Функция вызываемая при двойном щелчке по слоту - использование


void UseSlot( ESlot Slot )


{


//Если использована аптечка


if( Slot.Slot == ItemSlot.Health )


{


//Восполнить жизни и уничтожить предмет


Heal( Slot );


KillItem( Slot );


}


//Если тип используемого предмета - основное оружие


else if( Slot.Slot == ItemSlot.MainWeapon )


{


//Установить предмет как активное основное оружие


Swap( MainWeapon, Slot );





if( MainWeapon.Slot == PlayerChar.ActiveSlot )


{


PlayerChar.SetActiveWeapon( MainWeapon.Index );


}


PlayerChar.ActiveMainWeapon = MainWeapon.Index;


}


//Если тип используемого предмета - пистолет


else if( Slot.Slot == ItemSlot.Pistol )


{


//Установить предмет как активный пистолет


Swap( Pistol, Slot );





if( Pistol.Slot == PlayerChar.ActiveSlot )


{


PlayerChar.SetActiveWeapon( Pistol.Index );


}


PlayerChar.ActivePistol = Pistol.Index;


}


}


//Функция-обработчик нажатия на слот


void Slot_Click( EButton Sender )


{


ESlot Target = GetSlot( Sender.Name );


//Если нажали на слот


if( Target != null )


{


//Если в данный момент не перетаскивается предмет


if( DragItem == null )


{


//Данный предмет становится перетаскиваемым и меняется курсор


if( !Target.IsFree && Target != Drop && Target != Kill )


{


DragItem = Target;


DragItem.Button.Active = true;


ScreenControlManager.Instance.DefaultCursor = DragItem.Icon.BackTexture.Name;


}


FirstClickTime = Time;


}


//Если другой предмет уже перетаскивается


else


{


//Если время между двумя нажатиями на один слот меньше Delay


if( Target == DragItem && Time - FirstClickTime < Delay )


{


//Использовать предмет


UseSlot( DragItem );


}


//Если предмет перетащили на слот выброса


else if( Target == Drop )


{


//Выбросить предмет


DropItem( DragItem );


}


//Если предмет перетащили на слот уничтожения


else if( Target == Kill )


{


//Уничтожить предмет


KillItem( DragItem );


}


//Если предмет из обычного слота перетащили на слот основного оружия или наоборот


//и тип предмета подходит


else if( DragItem == MainWeapon && ( Target.Slot == ItemSlot.MainWeapon || Target.IsFree && Target != Pistol ) ||


Target == MainWeapon && DragItem.Slot == ItemSlot.MainWeapon )


{


Swap( DragItem, Target );





if( MainWeapon.Slot == PlayerChar.ActiveSlot || MainWeapon.Slot == ItemSlot.None )


{


PlayerChar.SetActiveWeapon( MainWeapon.Index );


}


PlayerChar.ActiveMainWeapon = MainWeapon.Index;


}


//Если предмет из обычного слота перетащили на слот пистолета или наоборот


//и тип предмета подходит


else if( DragItem == Pistol && ( Target.Slot == ItemSlot.Pistol || Target.IsFree && Target != MainWeapon ) ||


Target == Pistol && DragItem.Slot == ItemSlot.Pistol )


{


Swap( DragItem, Target );





if( Pistol.Slot == PlayerChar.ActiveSlot || Pistol.Slot == ItemSlot.None )


{


PlayerChar.SetActiveWeapon( Pistol.Index );


}


PlayerChar.ActivePistol = Pistol.Index;


}


//Если предмет из обычного слота перетащили на другой обычный слот


else if( DragItem != MainWeapon && DragItem != Pistol && Target != MainWeapon && Target != Pistol )


{


Swap( DragItem, Target );


}


//Курсор меняется обратно


ScreenControlManager.Instance.DefaultCursor = "CursorsDefault.png";


DragItem.Button.Active = false;


DragItem = null;


}


}


}


}


}





На 40


Последний раз редактировалось: Admin (Чт Дек 22, 2016 6:11 pm), всего редактировалось 1 раз(а)

Admin
Admin

Сообщения : 24
Рейтинг : 2770
Репутация : 0
Дата регистрации : 2016-12-15

https://fasendas.forum2x2.ru

Вернуться к началу Перейти вниз

Создание инвентаря (устаревшее) Empty Re: Создание инвентаря (устаревшее)

Сообщение автор Admin Ср Дек 21, 2016 5:51 pm

Создание инвентаря (часть 3).

Вносим изменения в стандартные классы

В этой части я расскажу, какие изменения необходимо внести в стандартные классы для корректной работы инвентаря на NeoAxis.

1. Файл PlayerCharacter.cs
Подключить библиотеку Engine.UISystem

Код:
using Engine.UISystem;




Добавить в пространство имен GameEntities объединение ItemSlot. Добавляется разделение предметов по типу использования.

Код:
namespace GameEntities
 {
     public enum ItemSlot
     {
         None,
         MainWeapon,
         Pistol,
         Health,
         Ammo,
     }
     …
 }




1.1. Класс PlayerCharacterType


Заменить стандартный список оружия

Код:

[FieldSerialize]
 List<WeaponItem> weapons = new List<WeaponItem>();

на адаптированный под инвентарь. Изменяется название и тип.

Код:

[FieldSerialize]
 List<InventoryItem> items = new List<InventoryItem>();

Добавить поле – размер инвентаря. Позволяет устанавливать размер инвентаря (нужно устанавливать значение равное количеству созданных слотов).

Код:

[FieldSerialize]
 int inventorySize;

Заменить стандартный класс, описывающий предмет-оружие

Код:

public class WeaponItem
 {
     [FieldSerialize]
     WeaponType weaponType;
 
     public WeaponType WeaponType
     {
         get { return weaponType; }
         set { weaponType = value; }
     }
 
     public override string ToString()
     {
         if( weaponType == null )
              return "(not initialized)";
         return weaponType.Name;
     }
 }

на новый класс, описывающий любой предмет инвентаря. Type – тип предмета (не *Item). ItemType - тип предмета (*Item). Slot – Тип предмета по применению. Icon – иконка премета в инвентаре. Hint – описание предмета в инвентаре.

Код:

 public class InventoryItem
 {
     [FieldSerialize]
     DynamicType type;
 
     [FieldSerialize]
     ItemType itemType;
 
     [FieldSerialize]
     ItemSlot slot;
 
     [FieldSerialize]
     string icon;
 
     [FieldSerialize]
     string hint;
 
     int normalBulletCount;
     int normalMagazineCount;
 
     int alternativeBulletCount;
     int alternativeMagazineCount;
 
     public DynamicType Type
     {
         get { return type; }
         set { type = value; }
     }
  
        public ItemType ItemType
     {
         get { return itemType; }
         set { itemType = value; }
     }
 
    public ItemSlot Slot
    {
         get { return slot; }
         set { slot = value; }
    }
 
     [Editor( typeof( EditorTextureUITypeEditor ), typeof( UITypeEditor ) )]
     public string Icon
     {
         get { return icon; }
         set { icon = value; }
     }
 
      public string Hint
     {
         get { return hint; }
         set { hint = value; }
     }
 
      [Browsable( false )]
    public int NormalBulletCount
    {
         get { return normalBulletCount; }
         set { normalBulletCount = value; }
    }
 
    [Browsable( false )]
    public int NormalMagazineCount
    {
         get { return normalMagazineCount; }
         set { normalMagazineCount = value; }
    }
 
     [Browsable( false )]
    public int AlternativeBulletCount
    {
         get { return alternativeBulletCount; }
         set { alternativeBulletCount = value; }
    }
 
    [Browsable( false )]
    public int AlternativeMagazineCount
    {
         get { return alternativeMagazineCount; }
         set { alternativeMagazineCount = value; }
    }
 
     public override string ToString()
    {
         if( type == null )
             return "(not initialized)";
         return type.Name;
    }
 }
 

1.2. Класс PlayerCharacter


Заменить стандартный список оружия

Код:

 List<WeaponItem> weapons;
 …
 [Browsable( false )]
 public List<WeaponItem> Weapons
 {
     get { return weapons; }
     set { weapons = value; }
 }

на список предметов инвентаря

Код:
List<InventoryItem> items;
 …
 [Browsable( false )]
 public List<InventoryItem> Items
 {
  get { return items; }
     set { items = value; }
 }


Заменить класс, описывающий предмет-оружие


Код:
public class WeaponItem
 {
     internal bool exists;
 
     internal int normalBulletCount;
     internal int normalMagazineCount;
 
     internal int alternativeBulletCount;
  internal int alternativeMagazineCount;
 
     public bool Exists
     {
         get { return exists; }
     }
 
     public int NormalBulletCount
     {
         get { return normalBulletCount; }
     }
 
     public int NormalMagazineCount
     {
         get { return normalMagazineCount; }
     }
 
     public int AlternativeBulletCount
     {
         get { return alternativeBulletCount; }
     }
 
     public int AlternativeMagazineCount
     {
         get { return alternativeMagazineCount; }
     }
 }


на класс, описывающий любой предмет инвентаря. Index – индекс предмета. Count – количество предметов (в 1 слоте).


Код:
public class InventoryItem
 {
     int index = -1;
     int count = 0;
 
     public int Index
     {
         get { return index; }
         set { index = value; }
     }
 
     public int Count
     {
         get { return count; }
         set { count = value; }
     }
 
     public void Copy( InventoryItem Source )
     {
         index = Source.Index;
         count = Source.Count;
     }
 
     public static void Swap( InventoryItem Item1, InventoryItem Item2 )
     {
         InventoryItem Temp = new InventoryItem();
         Temp.Copy( Item1 );
         Item1.Copy( Item2 );
         Item2.Copy( Temp );
     }
 }


Заменить во всем файле WeaponItem на InventoryItem.

Добавить необходимые данные и методы.

Текущее основное оружие


Код:
InventoryItem mainWeapon = new InventoryItem();
 [Browsable( false )]
 public InventoryItem MainWeapon
 {
     set {return mainWeapon; }
     set { mainWeapon = value; }
 }


 Текущий пистолет

Код:
InventoryItem pistol = new InventoryItem();
 [Browsable( false )]
 public InventoryItem Pistol
 {
     get { return pistol; }
     set { pistol = value; }
 }


Индекс текущего основного оружия


Код:
int activeMainWeapon = -1;
 [Browsable( false )]
 public int ActiveMainWeapon
 {
     get { return activeMainWeapon; }
     set { activeMainWeapon = value; }
 }


Индекс текущего пистолета


Код:
int activePistol = -1;
 [Browsable( false )]
 public int ActivePistol
 {
     get { return activePistol; }
     set { activePistol = value; }
 }


Слот активный в данный момент (основное оружие или пистолет)

 
Код:
ItemSlot activeSlot;
 [Browsable( false )]
 public ItemSlot ActiveSlot
 {
     get { return activeSlot; }
     set { activeSlot = value; }
 }


Размер инвентаря


Код:
[Browsable( false )]
 public int InventorySize
 {
     get { return Type.InventorySize;}
 }


Предмет находящийся под прицелом игрока на расстоянии использования

Код:
Item useItem;
 [Browsable( false )]
 public Item UseItem
 {
     get { return useItem; }
     set { useItem = value; }
 }


Объект класса инвентаря

Код:
EInventory inventory;
 [Browsable( false )]
 public EInventory Inventory
 {
     get { return inventory; }
     set { inventory = value; }
 }


Возвращает индекс свободного слота, если свободного слота нет то возвращает -1

Код:
public int GetFreeSlot()
 {
     for( int i = 0; i < Type.InventorySize; i++ )
     {
         if( items[ i ].Index == -1 )
         {
             return i;
         }
     }
     return -1;
 }


Возвращает индекс слота в котором хранятся патроны по индексу патронов. Сразу разъясню: индекс слота – это индекс в массиве слотов Items в классе PlayerCharacter, а индекс предмета (оружия, патронов и т.д.) – индекс в массиве предметов Items в классе PlayerCharacterType, который заполняется в Resource Editor’е.

Код:
public int GetBulletSlot( int bulletIndex )
 {
     for( int i = 0; i < InventorySize; i++ )
  {
         if( items[ i ].Index == bulletIndex )
         {
             return i;
         }
     }
     return -1;
 }


Возвращает индекс оружия по индексу патронов

Код:
public int GetBulletGun( int bulletIndex )
 {
     for( int i = 0; i < Type.Items.Count; i++ )
     {
         GunType gunType = Type.Items[ i ].Type as GunType;
         if( gunType != null )
         {
             if( gunType.NormalMode.BulletType == Type.Items[ bulletIndex ].Type ||
             gunType.AlternativeMode.BulletType == Type.Items[ bulletIndex ].Type )
             {
                 return i;
             }
         }
     }
     return -1;
 }


Обновляет количество патронов в инвентаре

Код:
public bool SetAmmoCount( BulletType bulletType, int count )
 {
     int index = GetItemIndex( bulletType );
     if( index != -1 )
     {
         int slot = GetBulletSlot( index );
         if( slot == -1 )
         {
             slot = GetFreeSlot();
             if( slot != -1 )
             {
                 items[ slot ].Index = index;
             }
             else
             {
                 return false;
             }
         }
         items[ slot ].Count = count;
     }
     return true;
 }


Заменить стандартный метод, возвращающий индекс оружия по его типу

Код:
public int GetWeaponIndex( WeaponType weaponType )
 {
     for( int n = 0; n < Type.Weapons.Count; n++ )
         if( Type.Weapons[ n ].WeaponType == weaponType )
             return n;
     return -1;
 }


на новый. Изменен тип аргумента.

Код:
public int GetItemIndex( DynamicType itemType )
 {
     for( int i = 0; i < Type.Items.Count; i++ )
     {
         if( Type.Items[ i ].Type == itemType )
         {
             return i;
         }
     }
     return -1;
 }


Заменить стандартный метод подбора оружия

Код:
public bool TakeWeapon( WeaponType weaponType )
 {
     int index = GetWeaponIndex( weaponType );
     if( index == -1 )
         return false;
 
     if( weapons[ index ].exists )
         return true;
 
     weapons[ index ].exists = true;
 
     SetActiveWeapon( index );
 
     return true;
 }


на новый.

Код:
public bool TakeItem( DynamicType itemType )
 {
  int index = GetItemIndex( itemType );
  if( index == -1 )
   return false;
 
     int Slot = GetFreeSlot();
     if( Slot != -1 )
     {
         items[ Slot ].Index = index;
         return true;
     }
   return false;
 }


Заменить стандартный метод подбора патронов

Код:
public bool TakeBullets( BulletType bulletType, int count )
 {
     bool taked = false;
 
     for( int n = 0; n < weapons.Count; n++ )
     {
         GunType gunType = Type.Weapons[ n ].WeaponType as GunType;
         if( gunType == null )
             continue;
 
         if( gunType.NormalMode.BulletType == bulletType )
         {
             if( weapons[ n ].normalBulletCount < gunType.NormalMode.BulletCapacity )
             {
                 taked = true;
                 weapons[ n ].normalBulletCount += count;
                 if( weapons[ n ].normalBulletCount > gunType.NormalMode.BulletCapacity )
                     weapons[ n ].normalBulletCount = gunType.NormalMode.BulletCapacity;
             }
         }
         if( gunType.AlternativeMode.BulletType == bulletType )
         {
             if( weapons[ n ].alternativeBulletCount < gunType.AlternativeMode.BulletCapacity )
             {
                 taked = true;
                 weapons[ n ].alternativeBulletCount += count;
                 if( weapons[ n ].alternativeBulletCount > gunType.AlternativeMode.BulletCapacity )
                     weapons[ n ].alternativeBulletCount = gunType.AlternativeMode.BulletCapacity;
             }
         }
     }
 
     if( ActiveWeapon != null )
     {
         Gun activeGun = activeWeapon as Gun;
         if( activeGun != null )
             activeGun.AddBullets( bulletType, count );
     }
 
     return taked;
 }


на новый

Код:
public bool TakeBullets( BulletType bulletType, int count )
 {
     bool taked = false;
 
     for( int i = 0;
 i < Type.Items.Count;
 i++ )
     {
         GunType gunType = Type.Items[ i ].Type as GunType;
         if( gunType == null )
             continue;
 
         if( gunType.NormalMode.BulletType == bulletType )
         {
             if( Type.Items[ i ].NormalBulletCount < gunType.NormalMode.BulletCapacity )
             {
                 int newCount = Type.Items[ i ].NormalBulletCount + count;
                 if( newCount > gunType.NormalMode.BulletCapacity )
                 {
                     newCount = gunType.NormalMode.BulletCapacity;
                 }
                 taked = SetAmmoCount( bulletType, newCount );
                 if( taked )
                 {
                     Type.Items[ i ].NormalBulletCount = newCount;
                 }
             }
         }
         if( gunType.AlternativeMode.BulletType == bulletType )
         {
             if( Type.Items[ i ].AlternativeBulletCount < gunType.AlternativeMode.BulletCapacity )
             {
                 int newCount = Type.Items[ i ].AlternativeBulletCount + count;
                 if( newCount > gunType.AlternativeMode.BulletCapacity )
                 {
                     newCount = gunType.AlternativeMode.BulletCapacity;
                 }
                 taked = SetAmmoCount( bulletType, newCount );
                 if( taked )
                 {
                     Type.Items[ i ].AlternativeBulletCount = newCount;
                 }
             }
         }
     }
     if( ActiveWeapon != null )
     {
         Gun activeGun = activeWeapon as Gun;
         if( activeGun != null )
         {
             activeGun.AddBullets( bulletType, count );
             if( activeGun.Type.NormalMode.BulletType == bulletType )
             {
                 SetAmmoCount( bulletType, activeGun.NormalMode.BulletCount );
             }
             else if( activeGun.Type.AlternativeMode.BulletType == bulletType )
             {
                 SetAmmoCount( bulletType, activeGun.AlternativeMode.BulletCount );
             }
         }
  }
  return taked;
 }


Заменить стандартный метод установки активного оружия

Код:
public bool SetActiveWeapon( int index )
 {
     if( index < -1 || index >= weapons.Count )
         return false;
 
     if( index != -1 )
         if( !weapons[ index ].exists )
             return false;
 
     if( activeWeapon != null )
     {
         activeWeapon.PreFire -= activeWeapon_PreFire;
         if( index != -1 && Type.Weapons[ index ].WeaponType == activeWeapon.Type )
             return true;
 
         foreach( MapObjectAttachedObject attachedObject in AttachedObjects )
         {
             MapObjectAttachedMapObject attachedMapObject = attachedObject as MapObjectAttachedMapObject;
             if( attachedMapObject == null )
                 continue;
              Weapon weapon = attachedMapObject.MapObject as Weapon;
             if( weapon == activeWeapon )
             {
                 Gun activeGun = activeWeapon as Gun;
                 if( activeGun != null )
                 {
                     int activeIndex = GetWeaponIndex( activeWeapon.Type );
                     weapons[ activeIndex ].normalMagazineCount = activeGun.NormalMode.BulletMagazineCount;
                     weapons[ activeIndex ].alternativeMagazineCount = activeGun.AlternativeMode.BulletMagazineCount;
                 }
                 Detach( attachedMapObject );
                 weapon.SetShouldDelete();
                 activeWeapon = null;
                 activeWeaponAttachedObject = null;
                 break;
             }
         }
     }
 
     if( index != -1 )
     {
         activeWeapon = (Weapon)Entities.Instance.Create( Type.Weapons[ index ].WeaponType, Parent );
 
         Gun activeGun = activeWeapon as Gun;
 
         if( activeGun != null )
         {
             activeGun.NormalMode.BulletCount = weapons[ index ].NormalBulletCount;
             activeGun.NormalMode.BulletMagazineCount = weapons[ index ].NormalMagazineCount;
 
             activeGun.AlternativeMode.BulletCount = weapons[ index ].AlternativeBulletCount;
             activeGun.AlternativeMode.BulletMagazineCount = weapons[ index ].AlternativeMagazineCount;
         }
 
         activeWeapon.PostCreate();
 
         activeWeaponAttachedObject = new MapObjectAttachedMapObject();
         activeWeaponAttachedObject.MapObject = activeWeapon;
         activeWeaponAttachedObject.BoneSlot = GetBoneSlotFromAttachedMeshes( activeWeapon.Type.BoneSlot );
         if( activeWeaponAttachedObject.BoneSlot == null ) activeWeaponAttachedObject.PositionOffset = Type.WeaponAttachPosition;
         Attach( activeWeaponAttachedObject );
 
         activeWeapon.PreFire += activeWeapon_PreFire;
     }
     return true;
 }


на новый

Код:
public bool SetActiveWeapon( int index )
 {
     if( index < -1 || index >= items.Count )         return false;
      if( activeWeapon != null )     {
         activeWeapon.PreFire -= activeWeapon_PreFire;
         if( index != -1 && Type.Items[ index ].Type.Name == activeWeapon.Type.Name )
              return true;
          foreach( MapObjectAttachedObject attachedObject in AttachedObjects )
         {
             MapObjectAttachedMapObject attachedMapObject = attachedObject as MapObjectAttachedMapObject;
             if( attachedMapObject == null )
                 continue;
              Weapon weapon = attachedMapObject.MapObject as Weapon;
             if( weapon == activeWeapon )
             {
                 Gun activeGun = activeWeapon as Gun;
                 if( activeGun != null )
                 {
                     int activeIndex = GetActiveWeapon();
                     Type.Items[ activeIndex ].NormalMagazineCount = activeGun.NormalMode.BulletMagazineCount;
                         Type.Items[ activeIndex ].AlternativeMagazineCount = activeGun.AlternativeMode.BulletMagazineCount;
                 }
 
                 Detach( attachedMapObject );
                 weapon.SetShouldDelete();
                 activeWeapon = null;
                 activeWeaponAttachedObject = null;
                 break;
             }
         }
     }
 
     if( index != -1 )
     {
         activeWeapon = (Weapon)Entities.Instance.Create( Type.Items[ index ].Type, Parent );
 
         Gun activeGun = activeWeapon as Gun;
 
         if( activeGun != null )
         {
             activeGun.NormalMode.BulletCount = Type.Items[ index ].NormalBulletCount;
             activeGun.NormalMode.BulletMagazineCount = Type.Items[ index ].NormalMagazineCount;
 
             activeGun.AlternativeMode.BulletCount = Type.Items[ index ].AlternativeBulletCount;
             activeGun.AlternativeMode.BulletMagazineCount = Type.Items[ index ].AlternativeMagazineCount;
         }
 
         activeWeapon.PostCreate();
 
         activeWeaponAttachedObject = new MapObjectAttachedMapObject();
         activeWeaponAttachedObject.MapObject = activeWeapon;
         activeWeaponAttachedObject.BoneSlot = GetBoneSlotFromAttachedMeshes( activeWeapon.Type.BoneSlot );
         if( activeWeaponAttachedObject.BoneSlot == null )         {
              activeWeaponAttachedObject.PositionOffset = Type.WeaponAttachPosition;
         }
         Attach( activeWeaponAttachedObject );
 
         activeWeapon.PreFire += activeWeapon_PreFire;
 
         SoundPlay3D( Type.Items[ index ].ItemType.SoundUse, .5f, true );
 
         WeaponTryReload();
     }
 
     return true;
 }


Заменить стандартный метод возвращающий индекс активного оружия

Код:
int GetActiveWeapon()
 {
     if( activeWeapon == null )
         return -1;
     for( int n = 0; n < Weapons.Count;
 n++ )
     {
         if( weapons[ n ].Exists )
         {
             if( Type.Weapons[ n ].WeaponType == activeWeapon.Type )
                 return n;
         }
     }
     return -1;
 }


на новый

Код:
int GetActiveWeapon()
 {
     if( activeSlot == ItemSlot.MainWeapon )
     {
         return activeMainWeapon;
     }
     else if( activeSlot == ItemSlot.Pistol )
     {
         return activePistol;
     }
     return -1;
 }


Заменить стандартный метод вызываемый при попытке выстрелить

Код:
void WeaponTryFire( bool alternative )
 {
     if( activeWeapon == null )
         return;
 
     //set real weapon fire direction
     {
         //!!!!!mb not true use DefaultCamera here
         Vec3 seeDir = SeePosition - RendererWorld.Instance.DefaultCamera.Position;
 
         Vec3 lookTo = SeePosition;
 
         for( int iter = 0; iter < 100; iter++ )         {
             activeWeapon.SetForceFireRotationLookTo( lookTo );
             Vec3 fireDir = activeWeapon.GetFireRotation( alternative ) * new Vec3( 1, 0, 0 );
             Degree angle = MathUtils.GetVectorsAngle( seeDir, fireDir );
 
             if( angle < 80 )
                 break;
 
             const float step = .3f;
             lookTo += seeDir * step;
         }
 
         activeWeapon.SetForceFireRotationLookTo( lookTo );
     }
 
     bool fired = activeWeapon.TryFire( alternative );
 
     Gun activeGun = activeWeapon as Gun;
     if( activeGun != null )
     {
         if( fired )
         {
             int index = GetWeaponIndex( activeWeapon.Type );
             weapons[ index ].normalBulletCount = activeGun.NormalMode.BulletCount;
             weapons[ index ].normalMagazineCount = activeGun.NormalMode.BulletMagazineCount;
             weapons[ index ].alternativeBulletCount = activeGun.AlternativeMode.BulletCount;
             weapons[ index ].alternativeMagazineCount = activeGun.AlternativeMode.BulletMagazineCount;
         }
     }
 }


на новый

Код:
void WeaponTryFire( bool alternative )
 {
     if( activeWeapon == null )
     return;
 
     //set real weapon fire direction
     {
     Vec3 seeDir = SeePosition - RendererWorld.Instance.DefaultCamera.Position;
 
     Vec3 lookTo = SeePosition;
 
     for( int iter = 0; iter < 100; iter++ )
     {
         activeWeapon.SetForceFireRotationLookTo( lookTo );
         Vec3 fireDir = activeWeapon.GetFireRotation( alternative ) * new Vec3( 1, 0, 0 );
         Degree angle = MathUtils.GetVectorsAngle( seeDir, fireDir );
 
         if( angle < 80 )
             break;
 
         const float step = .3f;
         lookTo += seeDir * step;
         }
 
         activeWeapon.SetForceFireRotationLookTo( lookTo );
     }
 
     bool fired = activeWeapon.TryFire( alternative );
 
     Gun activeGun = activeWeapon as Gun;
     if( activeGun != null )     {
         if( fired )
         {
             int index = GetItemIndex( activeWeapon.Type );
             Type.Items[ index ].NormalBulletCount = activeGun.NormalMode.BulletCount;
             Type.Items[ index ].NormalMagazineCount = activeGun.NormalMode.BulletMagazineCount;
             Type.Items[ index ].AlternativeBulletCount = activeGun.AlternativeMode.BulletCount;
             Type.Items[ index ].AlternativeMagazineCount = activeGun.AlternativeMode.BulletMagazineCount;
 
             int itemIndex = GetItemIndex( activeGun.Type.NormalMode.BulletType );
             ( index != -1 )
             {
                 int slot = GetBulletSlot( itemIndex );
                 if( slot != -1 )                 {
                     items[ slot ].Count = activeGun.NormalMode.BulletCount;
                 }
             }
         }
     }
 }


Заменить стандартный метод, обрабатывающий нажатие клавиш

Код:
protected override void OnIntellectCommand( Intellect.Command command )
 {
     base.OnIntellectCommand( command );
 
     if( command.KeyPressed )
     {
         if( command.Key >= GameControlKeys.Weapon1 && command.Key <= GameControlKeys.Weapon9 )
         {
             int index = (int)command.Key - (int)GameControlKeys.Weapon1;
             SetActiveWeapon( index );
         }
          if( command.Key == GameControlKeys.PreviousWeapon )
             SetActivePreviousWeapon();
         if( command.Key == GameControlKeys.NextWeapon )
             SetActiveNextWeapon();
         if( command.Key == GameControlKeys.Fire1 )
             WeaponTryFire( false );
         if( command.Key == GameControlKeys.Fire2 )
             WeaponTryFire( true );
         if( command.Key == GameControlKeys.Reload )
             WeaponTryReload();
     }
 }


на новый

Код:
protected override void OnIntellectCommand( Intellect.Command command )
 {
     base.OnIntellectCommand( command );
 
     if( command.KeyPressed )
     {
         if( command.Key == GameControlKeys.MainWeapon )
         {
             SetActiveWeapon( ActiveMainWeapon );
             ActiveSlot = ItemSlot.MainWeapon;
         }
         else if( command.Key == GameControlKeys.Pistol )
         {
             SetActiveWeapon( ActivePistol );
             ActiveSlot = ItemSlot.Pistol;
         }
         else if( command.Key == GameControlKeys.Fire1 )
         {
             WeaponTryFire( false );
         }
         else if( command.Key == GameControlKeys.Fire2 )
         {
             WeaponTryFire( true );
         }
         else if( command.Key == GameControlKeys.Reload )
         {
             WeaponTryReload();
         }
         else if( command.Key == GameControlKeys.Use )
         {
             if( UseItem != null )
             {
                 bool ret = UseItem.OnTake( this );
                 if( ret )
                 {
                     SoundPlay3D( UseItem.Type.SoundTake, .5f, true );
                     UseItem.Die();
                     UseItem = null;
                 }
             }
         }
         else if( command.Key == GameControlKeys.Inventory )
         {
             if( inventory != null )
             {
                 inventory.SetShouldDetach();
                 inventory = null;
 
                 EntitySystemWorld.Instance.Simulation = true;
                 EngineApp.Instance.MouseRelativeMode = true;
             }
             else
             {
                 inventory = new EInventory();
                 ScreenControlManager.Instance.Controls.Add( inventory );
 
                 EntitySystemWorld.Instance.Simulation = false;
                 EngineApp.Instance.MouseRelativeMode = false;
             }
         }
     }
 }





2. Класс ActionGameWindow


Добавить данные для хранения ссылки на игрока.

Код:
Unit PlayerUnit;
 PlayerCharacter PlayerChar;


В метод OnKeyDown добавить обработку нажатия клавиши Esc

Код:
if( e.Key == EKeys.Escape )
 {
     if( PlayerChar.Inventory != null )
     {
         PlayerChar.Inventory.SetShouldDetach();
         PlayerChar.Inventory = null;
 
         EntitySystemWorld.Instance.Simulation = true;
         EngineApp.Instance.MouseRelativeMode = true;
     }
 }


Добавить метод, возвращающий объект, находящийся под прицелом игрока, на расстоянии distance предмета

Код:
Body GetTarget( float distance )
 {
     Ray lookRay = RendererWorld.Instance.DefaultCamera.GetCameraToViewportRay( new Vec2( .5f, .5f ) );
 
     Body body = null;
 
     Vec3 lookFrom = lookRay.Origin;
     Vec3 lookDir = Vec3.Normalize( lookRay.Direction );
 
     PlayerUnit = GetPlayerUnit();
 
     RayCastResult[] piercingResult = PhysicsWorld.Instance.RayCastPiercing( new Ray( lookFrom, lookDir * distance ), (int)ContactGroup.CastOnlyContact );
 
     foreach( RayCastResult result in piercingResult )
     {
         bool ignore = false;
 
         MapObject obj = MapSystemWorld.GetMapObjectByBody( result.Shape.Body );
 
         Dynamic dynamic = obj as Dynamic;
         if( dynamic != null && PlayerUnit != null && dynamic.GetParentUnit() == GetPlayerUnit() )
             ignore = true;
 
         if( !ignore )
         {
             body = result.Shape.Body;
             return body;
         }
     }
     return body;
 }


Добавить в метод OnMouseMove код, записывающий в UseItem предмет который сейчас может использовать игрок.

Код:
Body body = GetTarget( 3.0f );
 if( body != null )
 {
     MapObject obj = MapSystemWorld.GetMapObjectByBody( body );
     if( obj != null && ( obj as GameGuiObject ) == null )
     {
         PlayerChar.UseItem = obj as Item;
          }
 }





3. Файл GameControlKeys.cs


Убрать

Код:
 [DefaultKeyboardMouseValue( EKeys.D1 )]
 Weapon1,
 [DefaultKeyboardMouseValue( EKeys.D2 )]
 Weapon2,
 [DefaultKeyboardMouseValue( EKeys.D3 )]
 Weapon3,
 [DefaultKeyboardMouseValue( EKeys.D4 )]
 Weapon4,
 [DefaultKeyboardMouseValue( EKeys.D5 )]
 Weapon5,
 [DefaultKeyboardMouseValue( EKeys.D6 )]
 Weapon6,
 [DefaultKeyboardMouseValue( EKeys.D7 )]
 Weapon7,
 [DefaultKeyboardMouseValue( EKeys.D8 )]
 Weapon8,
 [DefaultKeyboardMouseValue( EKeys.D9 )]
 Weapon9,


Добавить

Код:
[DefaultKeyboardMouseValue( EKeys.D1 )]
 MainWeapon,
 
 [DefaultKeyboardMouseValue( EKeys.D2 )]
 Pistol,
 
 [DefaultKeyboardMouseValue( EKeys.I )]
 Inventory,





4. Класс Item

В методе Take удалить все кроме

return false;






5. Класс WeaponItem


В методе OnTake заменить

Код:

Отсутствует

на Код:

Отсутствует


Цикл статей написан как ознокомительный, чтобы подать идею как данную проблему можно реализовать.

Admin
Admin

Сообщения : 24
Рейтинг : 2770
Репутация : 0
Дата регистрации : 2016-12-15

https://fasendas.forum2x2.ru

Вернуться к началу Перейти вниз

Создание инвентаря (устаревшее) Empty Re: Создание инвентаря (устаревшее)

Сообщение автор R.R.K Пт Дек 23, 2016 9:11 am

Всё не плохо, жаль что не весь урок... Думаю есть потенциал у этого урока перерасти в новую версию Smile
R.R.K
R.R.K

Сообщения : 6
Рейтинг : 2713
Репутация : 4
Дата регистрации : 2016-12-16
Возраст : 30

Вернуться к началу Перейти вниз

Создание инвентаря (устаревшее) Empty Re: Создание инвентаря (устаревшее)

Сообщение автор R.R.K Пт Дек 23, 2016 9:14 am

[Вы должны быть зарегистрированы и подключены, чтобы видеть эту ссылку]
R.R.K
R.R.K

Сообщения : 6
Рейтинг : 2713
Репутация : 4
Дата регистрации : 2016-12-16
Возраст : 30

Вернуться к началу Перейти вниз

Создание инвентаря (устаревшее) Empty Re: Создание инвентаря (устаревшее)

Сообщение автор Admin Сб Дек 24, 2016 10:19 am

Есть же кнопочка ютуба )))




Admin
Admin

Сообщения : 24
Рейтинг : 2770
Репутация : 0
Дата регистрации : 2016-12-15

https://fasendas.forum2x2.ru

Вернуться к началу Перейти вниз

Создание инвентаря (устаревшее) Empty Re: Создание инвентаря (устаревшее)

Сообщение автор Admin Сб Дек 24, 2016 10:21 am


Admin
Admin

Сообщения : 24
Рейтинг : 2770
Репутация : 0
Дата регистрации : 2016-12-15

https://fasendas.forum2x2.ru

Вернуться к началу Перейти вниз

Создание инвентаря (устаревшее) Empty Re: Создание инвентаря (устаревшее)

Сообщение автор Eris Пт Апр 13, 2018 7:43 pm

не думаю, что прям так уж устаревшее
Eris
Eris

Сообщения : 26
Рейтинг : 2704
Репутация : 1
Дата регистрации : 2017-01-08
Возраст : 40

Вернуться к началу Перейти вниз

Вернуться к началу

- Похожие темы

 
Права доступа к этому форуму:
Вы не можете отвечать на сообщения