Что такое префабы в расте
Создание префабов
префаб — это заготовка, состоящая из одного или нескольких объектов для быстрой вставки на карту
Просмотров : | 1877 ( +3 ) |
Скачиваний : | 0 |
Прислал / (а) : | SlaY_61 |
Дата создания : | 19.06.2011 12:24:25 |
Рейтинг : | Как Вы уже знаете, префаб — это заготовка, состоящая из одного или нескольких объектов для быстрой вставки на карту (например, стул, книжная полка, лампа, ящик и т.д.). Хранятся библиотеки префабов в файлах с расширением *.ol в директории «Hammer\prefabs». Вместе с Hammer’ом идут несколько библиотек с префабами,но они сделаны исключительно для HL2,поэтому для нас бесполезны. 1й способ, самый быстрый но очень некачественный. Выделяете нужные объекты (лкм + ctrl) и жмёте кнопку Create Prefab (находиться там где выбираються энтити). Минусы данного способа: при вставке на карту объект оказываеться не в нужном месте и его приходиться искать по карте. У каждого вставленного объекта будут одинаковые имена. 2й способ, правильный способ. Опять же выделяете нужные объекты пкм → copy (ctrl +c). File → New и вставляете на карту скопированные энтити. Передвинте точно на центр координат. Выделите вставленные объекты (если сняли выделение) и жмёте Create Prefab. Минусы данного способа: у каждого вставленного объекта будут одинаковые имена. 3й способ. Продвинутая версия. Опять же выделяете нужные объекты пкм → copy (ctrl +c). File → New и вставляете на карту скопированные энтити. Передвинте точно на центр координат. Например ваша лампочка называеться light и от кнопки идёт команда OnPressed > light > TurnOn. Берём и модифицируем наш префаб двумя символами «&i». Изменяем имя лампочки на light_&i и в команде то же меняем на light на light_&i ( OnPressed > light_&i > TurnOn ) light_1 и OnPressed > light_1 > TurnOn 2й префаб уже автоматически переименует имя и команду в итоге получится light_2 и OnPressed > light_2 > TurnOn и.т.д. Далее как всегда центруете это всё, выделяете и жмёте Create Prefab Rust WikiThis prefab can be used to apply text onto the in-game «G» map to mark custom locations/monuments. Displayed name is taken from the PrefabData «category» string. Source Map Editors can implement this feature by allowing the user to input the text into the monument_marker.prefab’s category section within the PrefabData. Softcore mode respawn pointsIn softcore mode players can respawn at Compound or Bandit Camp. These two respawn points are exposed to prefabs list and allows you to make custom safe zones compatible with Softcore-exclusive features. However, there are two important things to note: Bandit Camp respawn point:Compound respawn point:Softcore Reclaim PointWhen dying on a softcore server, players lose only 50% of their inventory. They can reclaim other half of their items at Reclaim Terminal that are located in safe zones. (Compound/Bandit Camp by default) You can set up your own reclaim points wherever you want using this: DropzoneInvisible point that Chinook-47 will use as a location for dropping the locked crate. Spawn PointAllows spawning players in exact spot if your map doesn’t have any appropriate spawn area or you want to make them spawn inside of a certain building or any other structure. If you want the game to determine spawn points naturally based on topology (Same as procedural maps) check out Making a valid spawn area. Information gathered provided by the Rust Map Making community. Rust WikiVolume Prefabs are a collection of various triggers that have their unique effects once players enter the prefab. Almost all volumes have a 1x1x1 cube collider. Almost all are completely invisible in-game but apply specific effects to the player when interacted with. Terrain TriggerAs long as a player remains inside of this trigger, collisions with the terrain will be ignored. If you want to make an entrance into a cave or other structure that needs the player to go through the terrain, this trigger is for you. Keep in mind that all underground structures must be inside of this trigger to prevent players from instantly dying due to antihack. The alternative solution is disabling the antihack protection for terrain using this parameter: +antihack.terrain_protection 0 Some prefabs like cave, sewer and bunker parts already contain a terrain trigger – you don’t need to add it again. You also cannot currently remove these built-in triggers from those prefabs. Water TriggerWhile players are inside of this trigger, visibility and interactions for all water related objects will be disabled, it will remove swimming and blurred vision but visibility becomes extremely dark as water triggers are usually needed underground. This may be helpful when your underground structure goes below the ocean level. Water Culling VolumePretty much does the same thing as Water Trigger, except it does not make the whole area around you dark. Invisible ColliderIt’s an invisible 1x1x1 meter cube that basically works like an invisible wall. Blocks projectiles and players. Prevent Player Movment(typo is a part of the prefab name) This works like an invisible collider but only for players – other forms of interactions with this wall (throwing/shooting through the wall, movement for NPCs) will remain active. You would most likely use this to stop a jump exploit in your monument without impacting PvP. Ladder TriggerWhen a player touches this trigger and they walk into the wall, the player will start climbing up. This will be helpful when you want to create a custom climbing prop or make static ladder prefabs usable. Environment VolumesThere are three environment volumes that change the visuals around you. This may be suitable for better immersion inside various types of design – buildings, underground structure, caves, etc. EnvironmentVolumeBuildingMakes the image slightly darker, just like when you are inside of a monument building or player base. Disables ambient sounds. (wind/bird sounds) EnvironmentVolumeUndergroundMakes everything completely dark, just like the inside of a Water Trigger, except you will be able to see and interact with the water inside this trigger. EnvironmentVolumeTraintunnles(that’s not a typo) Disables sun and sky dome, making everything around you covered in a darkness with an endless night. Probably has no use in open area, but will be a great addition for any large underground structures – this will avoid any kind of situations when sun might glitch through geometry beyond the shadow draw distance. Hurt TriggersTheir name are pretty much self-explanatory. Deals a certain amount of damage to player when colliding with this volume, higher volume type means more damage and lesser time to kill. There are four types of hurt triggers: You can see hurt triggers in action when trying to stand inside a working car shredder or under falling rocks at Giant Excavator Pit. Damage Trigger Death obviously just instantly kills anybody who colliders with this volume. (does not kill you if god mode enabled) Bandit Swamp Fog FXThis is a volumetric fog from the Bandit Camp monument. No description needed. SafezonesphereSafe Zone is a volume trigger a sphere collider (2 meter radius by default). Safe zone on custom maps works the same way as on outpost/bandit camp. You shoot – you die and receive a 30 minute long ban. Radiation SpheresThere are three types of radiation sources: They have a corresponding radiation level and will do slower or faster damage on player, depending on source type. When it comes to vanilla approach for radiation levels, it’s usually preferred to cover tier 3 monuments and best loot points with highest radiation level, especially if players are not meant to stay there for long, just like on top of launch site. Med and Low variants will fit the best for majority of your custom monuments. Comfort VolumeA sphere shaped volume that provides you comfort when staying inside of it. Perhaps a good thing to implement at safe zones for players to heal themselves slowly. Heat VolumeCube volume that slowly hurts a player when colliding with it, providing a specific PFX and sound effect of touching the fire. Good for implementation at custom fire sources. Trigger ForceAssumed to be a moving force just like on conveyor belts at Giant Excavator Pit. Their shape is not a standard one and may be confused to work with. (more details needs to be specified) Chair Invisible StaticAn invisible variant of a handmade chair. Doesn’t decay but can be destroyed with an ent kill command. Avoid using it on invisible chairs because there will be no way to add it back. Information gathered provided by the Rust Map Making community. Rust: & и ref в паттернах(продолжение) Разумеется сравнением дело не ограничивается. Как вы можете видеть в примере выше, объекты так же могут быть деструктурированы во время сопоставления (Some(value)) и их части присвоены другим переменным (value), которые могут быть далее использованы в соответствующей ветви match выражения. Изящно, не правда ли? В Расте сопоставление с образцом это хлеб и масло не только для match, но и для for, (if) let и даже для обыкновенных аргументов функции. Однако, долгое время я достаточно смутно представлял себе что происходит в случае когда мы добавляем к сопоставлению ссылки и заимствования. & и ref являются двумя «операторами» часто используемых при этом. Разнице между ними и будет посвящена данная статья. Вероятно вы уже достаточно хорошо знакомы с первым «оператором», используемым для создания ссылок и типов со ссылками. ref тоже весьма прозрачно намекает на связь со ссылками. Тем не менее эти два выражения играют очень разные роли при использовании внутри сопоставления. Дабы добавить путаницы достаточно часто они используются вместе: Отсутствие одного из них в лучшем случае будет отмечено компилятором вместе с предложением куда следует добавить то или иное выражение, что разумеется случается далеко не всегда. Поэтому весьма желательно понимать что здесь происходит на самом деле. Часть ссылки и часть сопоставленияРаст очень гибок в части того какие значения могут быть частью сопоставления. Вам придётся приложить недюжие усилия что бы найти нечто, что не может быть частью match выражения. И объекты, и ссылки на них могу быть без проблем использованы в нём: Однако, в предыдущем примере нам обычно неинтересна сама ссылка, но то куда она указывает: Как вы видите именно для этого и применяется амперсанд. Так же как и типы (Some, Ok или вышеобозначенный Foo), & указывает на то какое значение мы ожидаем при сопоставлении. Видя амперсанд программа знает, что мы хотим сопоставить ссылки на некие объекты, а не сами объекты. Но почему это различие между объектом и ссылкой на него так важно? В других местах Раст достаточно гибок в размытии границы между ссылками и самими объектами, например в случае вызова методов объекта. (механизм для этого называется «преобразованием при разыменовании» или по английски «Deref coercion» ) Однако, сопоставление с образцом, из-за возможности распаковки значений на их составные части, является деструктивной операцией. Всё к чему мы применим match (или иное похожее выражение) будет по умолчанию перемещено в данный блок: В полном соответствии с семантикой владения, match выражение предотвратит последующие попытки перемещения и в сущности поглотит объект. Таким образом, код выше выдаст следующее сообщение об ошибке: Так что как и Some амперсанд в сущности просто часть паттерна с которым мы производим сопоставление. И так же как и с Some и другими типами, мы имеет очевидную симметрию: если мы использовали & для создания значения, нам необходимо будет использовать амперсанд и для его распаковки.
Предотвращаем перемещениеОшибки, аналогичные приведённой выше, часто содержат полезные заметки: И пути потенциального исправления ошибки: Именно здесь и выходит на сцену ref. Сообщение говорит нам, что если мы добавим ключевое слово ref в предложенное место, мы сменим перемещение на заимствование для переменной использованной в данном сопоставлении. (в нашем случае это n) Как и раньше данная переменная захватит необходимое значение, но на этот раз без владения им. И это различие чрезвычайно важно. В отличии от амперсанда, ref не обозначает нечто с чем мы производим сопоставление. Оно никоим образом не влияет на то будет ли значение сопоставлено с данным паттерном или нет. Единственное, что оно меняет это то как части сопоставленного значения будут захвачены переменными паттерна: Первое это перемещение, второе это заимствование.
Используем их вместеДавайте теперь разберём что именно происходит в том запутанном примере из начала статьи: Т.к. мы знаем что ref никоим образом не влияет на сопоставится ли паттерн или нет, мы могли бы просто вставить что-то вроде &(a, b), данный вариант значительно читабельнее: ясно видно, что мы ожидаем ссылку на объект являющийся кортежем из двух элементов. Разумеется именно такие кортежи и являются членами вектора по которому происходит итерирование. Проблема в том, что без ref-ов мы пытаемся переместить значения кортежа внутрь цикла, но т.к. мы итерируем по &query_params, мы лишь заимствуем каждый из кортежей, поэтому такое перемещение на самом деле невозможно. По сути, это было бы классической попыткой перемещения значения из контекста заимствования. Но данное перемещение нам и не нужно. Единственное, что наш цикл делает, так это печатает значения, поэтому доступа к ним через ссылки будет более чем достаточно. И это как раз то, что ref нам даёт. Вернув обратно данное ключевое слово мы перейдём от перемещения к заимствованию. Rust Prefabs & MapsWelcome to RustPrefabs – FREE custom Rust prefabs and Rust maps designed by Admiral General Aladeen. The Rust prefabs are made for fun. When you download from this site, you agree upon these terms: Be sure to also visit our awesome tools like Rust Aim Trainer and Rust Raid Calculator. Please consider supporting by donating to us if you like these free Rust prefabs and Rust maps Fully custom PUBG map for Rust *UPDATED 2021*Started as a small project, but ended up as a 1:1 PUBG map — inspired by Erangel. The whole map is 6000m × 6000m with lots of custom monuments and other fun stuff. UPDATE 2021: Added lots of more custom monuments and fixed for the HDRP type servers. CG:GO DE_NUKE inspired arena *UPDATED 2021*Haven’t played CG:GO, but tried to make sort of a inspired/replica of the famous de_nuke map for arenas. UPDATE 2021: Fixed walls not showing on live servers and updated for the HDRP type servers. Aladeen’s ShackI wanted my own little cozy place to sit in and play some poker. And then this was made. Aladeen’s Loot ParadiseCustom house riddled with different loot rooms and a puzzle room. Aladeen’s StorageAnother “loot paradise” riddled with loot and puzzle room. Plain and simple. The Aladeen MapUseless, idiotic, low chance of survival, bad mountains. Just PERFECT! Enjoy the living hell from this badboy.
|