C#:
// Все права принадлежат дискорд сообществу https://discord.gg/VgNHPpNrz6
using Newtonsoft.Json;
using Rust;
using Oxide.Game.Rust.Cui;
using Debug = UnityEngine.Debug;
using System.Text;
using System.Drawing;
using Color = UnityEngine.Color;
using UnityEngine;
using System.Collections.Generic;
using System;
using Facepunch;
using System.Collections;
using VLB;
using Rust.Ai;
using Oxide.Core;
using Oxide.Core.Plugins;
namespace Oxide.Plugins {
[Info("IQBearRide", "rustmods.ru", "1.1.11")]
[Description("IQBearRide")]
class IQBearRide : RustPlugin {
void Unload() {
PluginData.SaveData();
_unloading = true;
InterfaceManager.DestroyAll();
try {
foreach (var value in _bearControllers) {
var bearController = value.Value;
if (bearController == null) continue;
bearController.SetRider(null);
var bear = bearController.BearOwner;
if (bear != null) {
var data = PluginData.Get(bear.net.ID.Value);
data.Health = bear.Health();
data.LastPosition = bear.transform.position;
bear.Kill();
}
}
_bearControllers.Clear();
}
catch(Exception e) {
Debug.LogError($"Error in Unload! Message: {e.Message}!\n{e.StackTrace}");
}
PluginData.SaveData();
_plugin = null;
}
[ConsoleCommand("iqbr.teddy")]
private void Console_YoungBearAdd(ConsoleSystem.Arg arg) {
BasePlayer player = arg.Player();
if (player != null && !permission.UserHasPermission(player.UserIDString, PermissionsGiveTeddyBear)) return;
if (arg.Args == null || arg.Args.Length < 1) {
if(player == null) Puts("Wrong syntax! Usage: iqbr.teddy <SteamID:Name:IP>");
else player.ConsoleMessage("Wrong syntax! Usage: iqbr.teddy <SteamID:Name:IP>");
return;
}
string playerid = arg.Args[0];
BasePlayer basePlayer = BasePlayer.Find(playerid);
if (basePlayer == null) {
if(player == null) Puts("Error! Player not found!");
else player.ConsoleMessage("Error! Player not found!");
return;
}
basePlayer.GiveItem(_config.YoungBearItem.ToItem());
if(player == null) Puts("Success! Item added to inventory!");
else player.ConsoleMessage("Success! Item added to inventory!");
}
void OnEntityBuilt(Planner plan, GameObject go) {
var item = plan.GetItem();
if (item == null) return;
var entity = go.ToBaseEntity();
if (entity == null) return;
var player = plan.GetOwnerPlayer();
if (player == null) return;
var pos = entity.transform.position;
if (_config.BearItem.CompareTo(item)) {
var bear = PluginData.ItemToBear(player.userID, item.uid.Value, pos, false);
NextTick(() => entity.Kill());
return;
}
if (_config.YoungBearItem.CompareTo(item)) {
var bear = PluginData.ItemToBear(player.userID, item.uid.Value, pos, true);
bear.OwnerID = player.userID;
NextTick(() => entity.Kill());
return;
}
}
private string GetImage(string name) {
string ID = (string)ImageLibrary?.Call("GetImage", name);
if (ID == "") ID = (string)ImageLibrary?.Call("GetImage", name) ?? ID;
return ID;
}
private PluginConfig GetDefaultConfig() {
return new PluginConfig {
BearItem = new CustomItem("Медведь | Bear", "stash.small", 2445048695), YoungBearItem = new CustomItem("Медвеженок | Teddy bear", "stash.small", 2445033042), BearDamage = new Dictionary<string, float>() {
["default"]
= 50f, ["player"] = 20f,
}
,
}
;
}
void Init() {
Unsubscribe("OnEntityTakeDamage");
permission.RegisterPermission(PermissionsGiveBear, this);
permission.RegisterPermission(PermissionsGiveTeddyBear, this);
}
[ConsoleCommand("iqbr.bear")]
private void Console_BearAdd(ConsoleSystem.Arg arg) {
BasePlayer player = arg.Player();
if (player != null) if(!permission.UserHasPermission(player.UserIDString, PermissionsGiveBear)) return;
if (arg.Args == null || arg.Args.Length < 1) {
if(player == null) Puts("Wrong syntax! Usage: iqbr.bear <SteamID:Name:IP>");
else player.ConsoleMessage("Wrong syntax! Usage: iqbr.bear <SteamID:Name:IP>");
return;
}
string playerid = arg.Args[0];
BasePlayer basePlayer = BasePlayer.Find(playerid);
if (basePlayer == null) {
if(player == null) Puts("Error! Player not found!");
else player.ConsoleMessage("Error! Player not found!");
return;
}
basePlayer.GiveItem(_config.BearItem.ToItem());
if(player == null) Puts("Success! Item added to inventory!");
else player.ConsoleMessage("Success! Item added to inventory!");
}
private static bool _unloading = false;
void OnEntitySpawned(BaseCorpse corpse) {
if (corpse != null && corpse.ShortPrefabName.Contains("bear")) {
int random = Core.Random.Range(0, 100);
if (random > _config.YoungDropChance) return;
var def = ItemManager.FindItemDefinition("glue");
ItemAmount itemBonus = new ItemAmount(def, 1f);
corpse.resourceDispenser.finishBonus.Add(itemBonus);
return;
}
}
private void ValidateConfig() {
if (Interface.Oxide.CallHook("OnConfigValidate") != null) {
PrintWarning("Using default configuration...");
_config = GetDefaultConfig();
}
}
object CanCombineDroppedItem(DroppedItem item, DroppedItem targetItem) {
if (_config.BearItem.CompareTo(item.item) || _config.YoungBearItem.CompareTo(item.item)) {
return false;
}
if (_config.BearItem.CompareTo(targetItem.item) || _config.YoungBearItem.CompareTo(targetItem.item)) {
return false;
}
return null;
}
private void StartPluginLoad() {
//if (ImageLibrary != null)
//{
//Load your images here
AddImage(_config.FollowImage);
AddImage(_config.RideImage);
AddImage(_config.TakeImage);
AddImage(_config.InventoryImage);
AddImage(_config.InstructionImage);
CheckStatus();
//}
//else
//{
// PrintError($"ImageLibrary not found! Please, check your plugins list.");
// _plugin.LogToFile("fjfjfj32341dsffagfdsa332572232", "IL NULLLLLLLLLLLLLL", this);
//}
}
private new void LoadDefaultMessages() {
lang.RegisterMessages(new Dictionary<string, string> {
["BEAR_FARM_WOOD"]
= "[Bear] Wood", ["BEAR_PICK_UP"] = "Only the owner can lift the bear", ["BEAR_PICK_UP_FULL_INVENTORY"] = "You need to pick up everything from the bear's inventory before picking it up", ["BEAR_GROWING_SECOND"] = "It will grow in <size=20>{0}</size> seconds", ["BEAR_GROWING_USE_MENU"] = "Press '<size=20>E</size>' for \ninteraction!", ["BEAR_MENU_TITLE"] = "BEAR MANAGEMENT",
}
, this);
lang.RegisterMessages(new Dictionary<string, string> {
["BEAR_FARM_WOOD"]
= "[Мишка] Дерево", ["BEAR_PICK_UP"] = "Только владелец может поднять медведя", ["BEAR_PICK_UP_FULL_INVENTORY"] = "Нужно забрать всё из инвентаря медведя перед тем как его поднять", ["BEAR_GROWING_SECOND"] = "Вырастет через <size=20>{0}</size> секунд", ["BEAR_GROWING_USE_MENU"] = "Нажмите '<size=20>E</size>' для \nвзаимодействия!", ["BEAR_MENU_TITLE"] = "УПРАВЛЕНИЕ МЕДВЕДЕМ",
}
, this, "ru");
PrintWarning(LanguageEn ? "The language file was uploaded successfully" : "Языковой файл загружен успешно");
}
private static bool _initiated = false;
private const String PermissionsGiveBear = "iqbearride.givebear";
private static PluginConfig _config;
object OnEntityTakeDamage(BaseCombatEntity entity, HitInfo hitInfo) {
if (hitInfo == null) return null;
var attacker = hitInfo.InitiatorPlayer;
if (attacker == null || !(attacker is BasePlayer)) return null;
{
Bear bear = entity as Bear;
if (bear != null && bear.OwnerID != 0 && bear.OwnerID.IsSteamId()) return false;
}
return null;
}
private static bool IsFriend(ulong player, ulong friend) {
if (player == friend) return true;
var team = RelationshipManager.ServerInstance.FindPlayersTeam(player);
if (team == null) return false;
return team.members.Contains(friend);
}
private class PluginConfig {
[JsonProperty(LanguageEn ? "Forbid the bear to defecate (true - yes / false - no)" : "Запретить медведю испражняться (true - да/false - нет)")]
public Boolean BlockDefecateBear = false;
[JsonProperty(LanguageEn ? "Chance of a bear cub falling out" : "Шанс выпадения медвеженка")]
public int YoungDropChance = 20;
[JsonProperty(LanguageEn ? "Make a bear immortal (true - yes/false - no)" : "Сделать бессмертным медведя (true - да/false - нет)")]
public Boolean Immortals = false;
[JsonProperty(LanguageEn ? "The number of hp of the bear" : "Количество хп медведя")]
public int MaxHealthAmount = 1200;
[JsonProperty(LanguageEn ? "How long does a bear grow in seconds" : "Сколько времени растёт медведь в секундах")]
public int GrowSeconds = 100;
[JsonProperty(LanguageEn ? "Walking speed" : "Скорость ходьбы")]
public float WalkSpeed = 5f;
[JsonProperty(LanguageEn ? "Leash speed" : "Скорость поводка")]
public float LeadSpeed = 7.5f;
[JsonProperty(LanguageEn ? "Running speed" : "Скорость бега")]
public float RunSpeed = 7.5f;
[JsonProperty(LanguageEn ? "Running speed with shift" : "Скорость бега с шифтом")]
public float SprintSpeed = 10f;
[JsonProperty(LanguageEn ? "Turning speed" : "Скорость поворота")]
public float RotateSpeed = 150;
[JsonProperty(LanguageEn ? "Step size up (If you don't know what it is, don't touch this function)" : "Размер шага вверх (Если вы не знаете что это такое, не трогайте данную функцию)")]
public float StepHigh = 1f;
[JsonProperty(LanguageEn ? "Step size down (If you don't know what it is, don't touch this function)" : "Размер шага вниз (Если вы не знаете что это такое, не трогайте данную функцию)")]
public float StepDown = 1f;
[JsonProperty(LanguageEn ? "Board size length (If you don't know what it is, don't touch this function)" : "Размер доски длина (Если вы не знаете что это такое, не трогайте данную функцию)")]
public float BoardForward = 1.5f;
[JsonProperty(LanguageEn ? "Board size width (If you don't know what it is, don't touch this function)" : "Размер доски ширина (Если вы не знаете что это такое, не трогайте данную функцию)")]
public float BoardRight = 0.2f;
[JsonProperty(LanguageEn ? "The maximum height that can climb" : "Максимальная высота на которую может залезть")]
public float MaxWallClimbSlope = 50f;
[JsonProperty(LanguageEn ? "The radius of checking for objects (If you don't know what it is, don't touch this function)" : "Радиус проверки на обьекты (Если вы не знаете что это такое, не трогайте данную функцию)")]
public float ObsCheckDis = 0.6f;
[JsonProperty(LanguageEn ? "The radius of the rotation balls check (If you do not know what it is, do not touch this function)" : "Радиус проверки шариков поворота (Если вы не знаете что это такое, не трогайте данную функцию)")]
public float RotSphereDis = 0.35f;
[JsonProperty(LanguageEn ? "Maximum depth" : "Максимальная глубина")]
public float MaxWaterDepth = 150f;
[JsonProperty(LanguageEn ? "Inventory Size" : "Размер инвентаря")]
public int InventorySize = 24;
[JsonProperty(LanguageEn ? "The damage inflicted is individual" : "Наносимый урон идивидуальный")]
public Dictionary<string, float> BearDamage;
[JsonProperty(LanguageEn ? "How much health to give when eating" : "Сколько здоровья давать при еде")]
public float EatHealAmount = 50f;
[JsonProperty(LanguageEn ? "IQ Chat : Custom prefix in the chat" : "IQChat : Кастомный префикс в чате")]
public String CustomPrefix = "[IQBearRide]";
[JsonProperty(LanguageEn ? "IQChat : Custom avatar in the chat (If required)" : "IQChat : Кастомный аватар в чате(Если требуется)")]
public String CustomAvatar = "0";
[JsonProperty(LanguageEn ? "IQChat : Use UI notifications" : "IQChat : Использовать UI уведомления")]
public Boolean UIAlertUse = false;
[JsonProperty(LanguageEn ? "Setting up the Bear Item" : "Настройка предмета Медведь")]
public CustomItem BearItem;
[JsonProperty(LanguageEn ? "Setting up the Bear Cub item" : "Настройка предмета Медвеженок")]
public CustomItem YoungBearItem;
[JsonProperty(LanguageEn ? "Picture To Follow" : "Картинка Следовать")]
public string FollowImage = "https://i.imgur.com/0sGNhqD.png";
[JsonProperty(LanguageEn ? "Picture to ride" : "Картинка Ехать")]
public string RideImage = "https://i.imgur.com/xar8gWn.png";
[JsonProperty(LanguageEn ? "Picture Raise" : "Картинка Поднять")]
public string TakeImage = "https://i.imgur.com/973xdCt.png";
[JsonProperty(LanguageEn ? "Picture Inventory" : "Картинка Инвентарь")]
public string InventoryImage = "https://i.imgur.com/OpjOCgL.png";
[JsonProperty(LanguageEn ? "Picture Instructions" : "Картинка Инструкции (С русским переводом - https://i.imgur.com/D5rIpyM.png)")]
public string InstructionImage = "https://i.imgur.com/32JQy4R.png";
}
private static void DrawText(BasePlayer player, Vector3 position, string text, float time = 1) {
player.SetPlayerFlag(BasePlayer.PlayerFlags.IsAdmin, true);
player.SendEntityUpdate();
player.SendConsoleCommand("ddraw.text", time, Color.white, position, text);
player.SendConsoleCommand("camspeed 0");
if (player.Connection.authLevel < 2) player.SetPlayerFlag(BasePlayer.PlayerFlags.IsAdmin, false);
player.SendEntityUpdate();
}
private void DrawUI_BearMenu(BasePlayer player, ulong bear) {
var controller = _bearControllers[bear];
string gui = InterfaceManager.GetInterface("BearMain");
gui = gui.Replace("{bear}", bear.ToString());
gui = gui.Replace("%TEXT%", GetLang("BEAR_MENU_TITLE", player.UserIDString));
gui = gui.Replace("{LeadColor}", GetColor(controller.HasLead() ? "#18CA77" : "#CA2539", 0.8f));
CuiHelper.DestroyUi(player, InterfaceManager.UI_Layer);
CuiHelper.AddUi(player, gui);
}
/// </summary>
///Обновление 1.0.x
/// - Поправлено уведомление о добыче мишкой
/// - Исправления после обновления игры
/// - Добавлена возможность запретить медведю испражняться
[PluginReference]
Plugin IQChat, StackSizeController;
private void OnEntityDismounted(BaseVehicleSeat chair, BasePlayer player) {
if (chair == null || player == null) return;
var bear = chair.parentEntity.Get(true) as Bear;
if (bear == null) return;
var controller = bear.GetComponent<BearController>();
if (controller == null) return;
controller.SetRider(null);
CuiHelper.DestroyUi(player, InterfaceManager.UI_Instruction);
}
private static string GetNameByURL(string url) {
var splitted = url.Split('/');
var endUrl = splitted[splitted.Length - 1];
var name = endUrl.Split('.')[0];
return name;
}
protected override void SaveConfig() {
Config.WriteObject(_config);
}
private void OpenContainer(BasePlayer player, ItemContainer container, int capacity) {
var loot = player.inventory.loot;
var position = player.transform.position - new Vector3(0, 500, 0);
var entity = GameManager.server.CreateEntity("assets/prefabs/visualization/sphere.prefab", position);
if (entity == null) {
return;
}
entity.enableSaving = false;
entity.Spawn();
container.entityOwner = entity;
container.playerOwner = player;
container.capacity = capacity;
foreach (var item in container.itemList.ToArray()) {
if (item.position >= capacity) {
item.RemoveFromContainer();
item.MoveToContainer(container);
}
}
entity.StartCoroutine(UserChecker(player, entity));
_plugin.timer.Once(0.5f, () => {
if (player == null) {
return;
}
loot.Clear();
loot.PositionChecks = false;
loot.entitySource = entity;
loot.itemSource = (Item) null;
loot.MarkDirty();
loot.AddContainer(container);
loot.SendImmediate();
player.ClientRPCPlayer(null, player, "RPC_OpenLootPanel", "generic");
player.SendNetworkUpdateImmediate();
}
);
}
private void OnDispenserBonus(ResourceDispenser dispenser, BasePlayer player, Item item) {
if (dispenser.name.Contains("bear.corpse") == false) return;
if (item.info.shortname != "glue") return;
item.Remove();
player.GiveItem(_config.YoungBearItem.ToItem());
return;
}
private static Dictionary<ulong, BearController> _bearControllers = new Dictionary<ulong, BearController>();
private static IQBearRide _plugin;
void OnServerInitialized() {
if (ImageLibrary == null) {
NextTick(() => {
PrintError(LanguageEn ? "For the plugin to work correctly, you need to install the Image Library plugin (https://umod.org/plugins/image-library)" : "Для корректной работы плагина требуется установить плагин ImageLibrary (https://umod.org/plugins/image-library)");
Interface.Oxide.UnloadPlugin(Name);
}
);
}
_plugin = this;
_unloading = false;
StartPluginLoad();
}
private class InterfaceManager {
public static InterfaceManager Instance;
public const string UI_Layer = "UI_BearRide";
public const string UI_Instruction = "UI_Instruction_Bear";
public Dictionary<string, string> Interfaces;
public InterfaceManager() {
Instance = this;
Interfaces = new Dictionary<string, string>();
BuildInterface();
BuildInstruction();
}
public static void AddInterface(string name, string json) {
if (Instance.Interfaces.ContainsKey(name)) {
_plugin.PrintError($"Error! Tried to add existing cui elements! -> {name}");
return;
}
Instance.Interfaces.Add(name, json);
}
public static string GetInterface(string name) {
string json = string.Empty;
if (Instance.Interfaces.TryGetValue(name, out json) == false) {
_plugin.PrintWarning($"Warning! UI elements not found by name! -> {name}");
}
return json;
}
public static void DestroyAll() {
for (var i = 0; i < BasePlayer.activePlayerList.Count; i++) {
var player = BasePlayer.activePlayerList[i];
CuiHelper.DestroyUi(player, UI_Layer);
CuiHelper.DestroyUi(player, UI_Instruction);
}
}
private void BuildInstruction() {
CuiElementContainer container = new CuiElementContainer() {
{
new CuiPanel {
CursorEnabled = false, RectTransform = {
AnchorMin = "0.5 0.5", AnchorMax = "0.5 0.5", OffsetMin = "300.426 -343.7", OffsetMax = "427.374 -261.8922572"
}
, Image = {
Color = "0 0 0 0"
}
}
, "Overlay", UI_Instruction
}
, {
new CuiElement {
Parent = UI_Instruction, Name = "PNG_Instruction", Components = {
new CuiRawImageComponent {
Color = "1 1 1 1", Png = _plugin.GetImage(GetNameByURL(_config.InstructionImage)),
}
, new CuiRectTransformComponent {
AnchorMin = "0.5 0.5", AnchorMax = "0.5 0.5", OffsetMin = "-17.806 -40.9042572", OffsetMax = "63.476 13.177"
}
}
,
}
}
}
;
AddInterface("BearInstruciont", container.ToJson());
}
private void BuildInterface() {
CuiElementContainer container = new CuiElementContainer() {
{
new CuiPanel {
CursorEnabled = true, RectTransform = {
AnchorMin = $"0.5 0.5", AnchorMax = $"0.5 0.5", OffsetMin = "-165 -60", OffsetMax = "165 70"
}
, Image = {
Color = "0 0 0 0"
}
}
, "Overlay", UI_Layer
}
, {
new CuiButton {
RectTransform = {
AnchorMin = $"-100 -100", AnchorMax = $"100 100"
}
, Button = {
Color = "0 0 0 0", Close = UI_Layer, Command = "UI_BearControl close {bear}"
}
, Text = {
Text = ""
}
}
, UI_Layer
}
, {
new CuiElement {
Parent = UI_Layer, Name = $"{UI_Layer}.LogoBar", Components = {
new CuiImageComponent {
Color = "0 0 0 0"
}
, new CuiRectTransformComponent {
AnchorMin = $"0 1", AnchorMax = $"1 1", OffsetMin = "5 -60", OffsetMax = "-5 -60"
}
,
}
}
}
, {
new CuiElement {
Parent = $"{UI_Layer}.LogoBar", Components = {
new CuiTextComponent {
Text = "%TEXT%", Align = TextAnchor.MiddleCenter, Color = GetColor("#FFFFFF", 1f), FontSize = 14, Font = "robotocondensed-bold.ttf"
}
, new CuiRectTransformComponent {
AnchorMin = $"0 0", AnchorMax = $"1 1", OffsetMax = "0 40"
}
, new CuiOutlineComponent {
Color = "0 0 0 1", Distance = "0.2 0.2"
}
}
}
}
, {
new CuiElement {
Parent = UI_Layer, Name = $"{UI_Layer}.Follow", Components = {
new CuiImageComponent {
Color = "{LeadColor}"
}
, new CuiRectTransformComponent {
AnchorMin = $"0 1", AnchorMax = $"0 1", OffsetMin = "60 -100", OffsetMax = "110 -50"
}
,
}
}
}
, {
new CuiElement {
Parent = $"{UI_Layer}.Follow", Components = {
new CuiRawImageComponent {
Png = _plugin.GetImage(GetNameByURL(_config.FollowImage))
}
, new CuiRectTransformComponent {
AnchorMin = $"0 0", AnchorMax = $"1 1"
}
}
}
}
, {
new CuiButton {
RectTransform = {
AnchorMin = $"0 0", AnchorMax = $"1 1", OffsetMin = "0 0", OffsetMax = "1 1"
}
, Button = {
Color = "0 0 0 0", Command = "UI_BearControl lead {bear}", Close = UI_Layer
}
, Text = {
Text = ""
}
}
, $"{UI_Layer}.Follow"
}
, {
new CuiElement {
Parent = UI_Layer, Name = $"{UI_Layer}.Ride", Components = {
new CuiImageComponent {
Color = GetColor("#CA2539", 0.8f)
}
, new CuiRectTransformComponent {
AnchorMin = $"0 1", AnchorMax = $"0 1", OffsetMin = "115 -100", OffsetMax = "165 -50"
}
,
}
}
}
, {
new CuiElement {
Parent = $"{UI_Layer}.Ride", Components = {
new CuiRawImageComponent {
Png = _plugin.GetImage(GetNameByURL(_config.RideImage))
}
, new CuiRectTransformComponent {
AnchorMin = $"0 0", AnchorMax = $"1 1",
}
}
}
}
, {
new CuiButton {
RectTransform = {
AnchorMin = $"0 0", AnchorMax = $"1 1",
}
, Button = {
Color = "0 0 0 0", Command = "UI_BearControl ride {bear}", Close = UI_Layer
}
, Text = {
Text = ""
}
}
, $"{UI_Layer}.Ride"
}
, {
new CuiElement {
Parent = UI_Layer, Name = $"{UI_Layer}.Inventory", Components = {
new CuiImageComponent {
Color = GetColor("#CA2539", 0.8f)
}
, new CuiRectTransformComponent {
AnchorMin = $"0 1", AnchorMax = $"0 1", OffsetMin = "170 -100", OffsetMax = "220 -50"
}
,
}
}
}
, {
new CuiElement {
Parent = $"{UI_Layer}.Inventory", Components = {
new CuiRawImageComponent {
Png = _plugin.GetImage(GetNameByURL(_config.InventoryImage))
}
, new CuiRectTransformComponent {
AnchorMin = $"0 0", AnchorMax = $"1 1"
}
}
}
}
, {
new CuiButton {
RectTransform = {
AnchorMin = $"0 0", AnchorMax = $"1 1"
}
, Button = {
Color = "0 0 0 0", Command = "UI_BearControl inventory {bear}", Close = UI_Layer
}
, Text = {
Text = ""
}
}
, $"{UI_Layer}.Inventory"
}
, {
new CuiElement {
Parent = UI_Layer, Name = $"{UI_Layer}.Take", Components = {
new CuiImageComponent {
Color = GetColor("#CA2539", 0.8f)
}
, new CuiRectTransformComponent {
AnchorMin = $"0 1", AnchorMax = $"0 1", OffsetMin = "225 -100", OffsetMax = "275 -50"
}
,
}
}
}
, {
new CuiElement {
Parent = $"{UI_Layer}.Take", Components = {
new CuiRawImageComponent {
Png = _plugin.GetImage(GetNameByURL(_config.TakeImage))
}
, new CuiRectTransformComponent {
AnchorMin = $"0 0", AnchorMax = $"1 1"
}
}
}
}
, {
new CuiButton {
RectTransform = {
AnchorMin = $"0 0", AnchorMax = $"1 1",
}
, Button = {
Color = "0 0 0 0", Command = "UI_BearControl pickup {bear}", Close = UI_Layer
}
, Text = {
Text = ""
}
}
, $"{UI_Layer}.Take"
}
,
}
;
AddInterface("BearMain", container.ToJson());
}
}
private const String PermissionsGiveTeddyBear = "iqbearride.giveteddy";
private class BearController : MonoBehaviour {
private void ModifyRunState(int dir) {
if (this.currentRunState == BaseRidableAnimal.RunState.stopped && dir < 0 || this.currentRunState == BaseRidableAnimal.RunState.sprint && dir > 0) return;
this.SwitchMoveState(this.currentRunState + dir);
}
private bool AttackReady() {
return Time.realtimeSinceStartup >= nextAttackTime;
}
public void AnimalDecay() {
if (BearOwner.healthFraction == 0.0 || BearOwner.IsDestroyed || (Time.time < (lastInputTime + 600.0) || Time.time < (lastEatTime + 600.0))) return;
BearOwner.Hurt(BearOwner.MaxHealth() * (1f / BaseRidableAnimal.decayminutes) * (!BearOwner.IsOutside() ? 1f : 0.5f), DamageType.Decay, BearOwner, false);
}
private float nextAttackTime;
public float GetDesiredVelocity() {
return this.MoveStateToVelocity(this.currentRunState);
}
private void Start() {
var data = PluginData.Get(BearOwner.net.ID.Value);
if (data.GrowSeconds > 0) {
ShouldGrow = true;
GrowingSeconds = data.GrowSeconds;
StartCoroutine(DoGrow(data));
}
}
private float GetRunSpeed() {
return MoveStateToVelocity(currentRunState);
}
public bool HasDriver() {
return _rider != null;
}
public float MoveStateToVelocity(BaseRidableAnimal.RunState stateToCheck) {
float num;
switch (stateToCheck) {
case BaseRidableAnimal.RunState.walk : num = HasLead() ? leadSpeed : walkSpeed;
break;
case BaseRidableAnimal.RunState.run : num = runSpeed;
break;
case BaseRidableAnimal.RunState.sprint : num = sprintSpeed;
break;
default : num = 0.0f;
break;
}
return num;
}
public OBB WorldSpaceBounds() {
return new OBB(BearOwner.transform.position, BearOwner.transform.lossyScale, BearOwner.transform.rotation, BearOwner.bounds);
}
private float desiredRotation;
private float lastDdrawUpdate = Time.time;
public virtual float WaterFactor() {
return WaterLevel.Factor(this.WorldSpaceBounds().ToBounds(), BearOwner);
}
private float nextEatTime = Time.time;
private BaseRidableAnimal.RunState StateFromSpeed(float speedToUse) {
if ((double) speedToUse <= (double) this.MoveStateToVelocity(BaseRidableAnimal.RunState.stopped)) return BaseRidableAnimal.RunState.stopped;
if ((double) speedToUse <= (double) this.MoveStateToVelocity(BaseRidableAnimal.RunState.walk)) return BaseRidableAnimal.RunState.walk;
return (double) speedToUse <= (double) this.MoveStateToVelocity(BaseRidableAnimal.RunState.run) ? BaseRidableAnimal.RunState.run : BaseRidableAnimal.RunState.sprint;
}
private float ObstacleSpeed(float obstacleDistance) {
float num = 0;
if (obstacleDistance > 3) {
float runSpeed = GetRunSpeed();
num = runSpeed * obstacleDistance / 30;
if (obstacleDistance > 4) {
num = runSpeed;
}
}
return num;
}
private Vector3 targetUp = Vector3.up;
public float maxWaterDepth = _config.MaxWaterDepth;
private float timeInMoveState;
public TreeEntity CheckTree(Vector3 pos, Vector3 aim) {
RaycastHit[] hit;
hit = Physics.SphereCastAll(pos, 2.5f, Vector3.forward, 2.5f, LayerMask.GetMask("Tree"));
foreach (var hits in hit) {
if (hits.GetEntity() == null) continue;
TreeEntity Tree = hits.GetEntity() as TreeEntity;
if (Tree == null) continue;
return Tree;
}
return null;
}
public DamageType AttackDamageType = DamageType.Bite;
private bool IsVisible(Ray ray, float maxDistance = float.PositiveInfinity) {
RaycastHit hit;
if (ray.origin.IsNaNOrInfinity() || ray.direction.IsNaNOrInfinity() || ray.direction == Vector3.zero || !BearOwner.WorldSpaceBounds().Trace(ray, out hit, maxDistance)) return false;
RaycastHit hitInfo;
if (!GamePhysics.Trace(ray, 0.0f, out hitInfo, maxDistance, 1218519041)) return true;
var entity = hitInfo.GetEntity();
return entity == BearOwner || entity != null && (bool) BearOwner.GetParentEntity() && (BearOwner.GetParentEntity().EqualNetID(entity) && hitInfo.IsOnLayer(Rust.Layer.Vehicle_Detailed)) || hitInfo.distance > (double) hit.distance;
}
private float backwardHeldSeconds;
private float lastForwardPressedTime;
private bool IsVisible(Vector3 position, Vector3 target, float maxDistance = float.PositiveInfinity) {
var vector3_1 = target - position;
var magnitude = vector3_1.magnitude;
if (magnitude < Mathf.Epsilon) return true;
var direction = vector3_1 / magnitude;
var vector3_2 = direction * Mathf.Min(magnitude, 0.01f);
return IsVisible(new Ray(position + vector3_2, direction), maxDistance);
}
private void RiderInput(InputState inputState, BasePlayer player) {
float num1 = UnityEngine.Time.time - this.lastInputTime;
this.lastInputTime = UnityEngine.Time.time;
float num2 = Mathf.Clamp(num1, 0.0f, 1f);
Vector3 zero = Vector3.zero;
this.timeInMoveState += num2;
if (inputState == null) return;
if (inputState.IsDown(BUTTON.FORWARD)) {
this.lastForwardPressedTime = UnityEngine.Time.time;
this.forwardHeldSeconds += num2;
}
else this.forwardHeldSeconds = 0.0f;
if (inputState.IsDown(BUTTON.BACKWARD)) {
this.lastBackwardPressedTime = UnityEngine.Time.time;
this.backwardHeldSeconds += num2;
}
else this.backwardHeldSeconds = 0.0f;
if (inputState.IsDown(BUTTON.SPRINT)) {
this.lastSprintPressedTime = UnityEngine.Time.time;
this.sprintHeldSeconds += num2;
}
else this.sprintHeldSeconds = 0.0f;
if ((double) this.forwardHeldSeconds > 0.0) {
if (this.currentRunState == BaseRidableAnimal.RunState.stopped) this.SwitchMoveState(BaseRidableAnimal.RunState.walk);
else if (this.currentRunState == BaseRidableAnimal.RunState.walk) {
if ((double) this.sprintHeldSeconds > 0.0) this.SwitchMoveState(BaseRidableAnimal.RunState.run);
}
else if (this.currentRunState == BaseRidableAnimal.RunState.run && (double) this.sprintHeldSeconds > 1.0) // && this.CanInitiateSprint())
this.SwitchMoveState(BaseRidableAnimal.RunState.sprint);
}
else if ((double) this.backwardHeldSeconds > 1.0) {
this.ModifyRunState(-1);
this.backwardHeldSeconds = 0.1f;
}
else if ((double) this.backwardHeldSeconds == 0.0 && (double) this.forwardHeldSeconds == 0.0 && ((double) this.timeInMoveState > 1.0 && this.currentRunState != BaseRidableAnimal.RunState.stopped)) this.ModifyRunState(-1);
if (this.currentRunState == BaseRidableAnimal.RunState.sprint && ( /*!this.CanSprint() ||*/
(double) UnityEngine.Time.time - (double) this.lastSprintPressedTime > 5.0)) this.ModifyRunState(-1);
if (inputState.IsDown(BUTTON.RIGHT)) {
this.desiredRotation = 1f;
}
else if (inputState.IsDown(BUTTON.LEFT)) {
this.desiredRotation = -1f;
}
else this.desiredRotation = 0.0f;
}
public void Sphere(BasePlayer player, Vector3 pos, float radius, Color color, float duration) {
player.SendConsoleCommand("ddraw.sphere", duration, color, pos, radius);
}
private TimeUntil dropUntilTime;
private void EatNearbyFood() {
if (Time.time < (double) nextEatTime || currentRunState != BaseRidableAnimal.RunState.stopped) return;
var num = BearOwner.healthFraction;
nextEatTime = (float) (Time.time + (double) Core.Random.Range(2f, 3f) + Mathf.InverseLerp(0.5f, 1f, num) * 4.0);
if (num >= 1.0) return;
var list = Pool.GetList<BaseEntity>();
var transform1 = BearOwner.transform;
Vis.Entities(transform1.position + transform1.forward * 1.5f, 2f, list, 67109377);
list.Sort((a, b) => (b is DroppedItem).CompareTo(a is DroppedItem));
foreach (var baseEntity in list) if (!baseEntity.isClient) {
var droppedItem = baseEntity as DroppedItem;
if ((bool) droppedItem && droppedItem.item != null && droppedItem.item.info.category == ItemCategory.Food) {
var component = droppedItem.item.info.GetComponent<ItemModConsumable>();
if ((bool) component) {
lastEatTime = Time.time;
BearOwner.Heal(_config.EatHealAmount);
BearOwner.SignalBroadcast(BaseEntity.Signal.Attack);
BearOwner.ClientRPC(null, "Attack", BearOwner.ServerPosition + Vector3.forward);
droppedItem.item.UseItem();
if (droppedItem.item.amount <= 0) {
droppedItem.Kill();
}
break;
}
}
var collectibleEntity = baseEntity as CollectibleEntity;
if ((bool) collectibleEntity && collectibleEntity.IsFood()) {
collectibleEntity.DoPickup(null);
break;
}
var growableEntity = baseEntity as GrowableEntity;
if ((bool) growableEntity && growableEntity.CanPick()) {
growableEntity.PickFruit(null);
break;
}
}
Pool.FreeList(ref list);
}
public float ObstacleDistanceCheck(float speed = 10f) {
int num1 = Mathf.Max(2, Mathf.Min((int) speed, 10));
float num2 = 0.5f;
int num3 = Mathf.CeilToInt((float) num1 / num2);
float num4 = 0.0f;
Vector3 direction = QuaternionEx.LookRotationForcedUp(BearOwner.transform.forward, Vector3.up) * Vector3.forward;
Vector3 vector3_1 = BearOwner.transform.position + BearOwner.transform.forward * 0.2f + new Vector3(0, 0.3f);
vector3_1.y = BearOwner.transform.position.y;
Vector3 up = BearOwner.transform.up;
for (int index1 = 0; index1 < num3; ++index1) {
float maxDistance = num2;
bool flag = false;
float num5 = 0.0f;
Vector3 pos1 = Vector3.zero;
Vector3 normal1 = Vector3.up;
Vector3 a = vector3_1;
Vector3 origin = a + Vector3.up * (this.maxStepHeight + this.obstacleDetectionRadius);
Vector3 vector3_2 = a + direction * maxDistance;
float num6 = this.maxStepDownHeight + this.obstacleDetectionRadius;
RaycastHit hitInfo;
if (UnityEngine.Physics.SphereCast(origin, this.obstacleDetectionRadius, direction, out hitInfo, maxDistance, 1486954753)) {
num5 = hitInfo.distance;
pos1 = hitInfo.point;
normal1 = hitInfo.normal;
flag = true;
}
if (!flag) {
if (!TransformUtil.GetGroundInfo(vector3_2 + Vector3.up * 2f, out pos1, out normal1, 2f + num6, (LayerMask) 278986753, (Transform) null)) return num4;
num5 = Vector3.Distance(a, pos1);
if (WaterLevel.Test(pos1 + Vector3.one * this.maxWaterDepth, true, BearOwner)) {
return num4;
}
flag = true;
}
if (flag) {
double num7 = (double) Vector3.Angle(up, normal1);
float num8 = Vector3.Angle(normal1, Vector3.up);
if (num7 > maxWallClimbSlope || (double) num8 > (double) this.maxWallClimbSlope) {
Vector3 vector3_3 = normal1;
float y = pos1.y;
int num9 = 1;
for (int index2 = 0; index2 < this.normalOffsets.Length; ++index2) {
Vector3 vector3_4 = vector3_2 + this.normalOffsets[index2].x * BearOwner.transform.right;
float nu
// ... [Code preview truncated due to length. Full source in attached file] ...