Для своего предыдущего поста мне потребовалась подсветка кода. первым делом я решил найти готовые решения, но единственное которое мне понравилось было жутко медленным, и трудным в кастомизации. поэтому я решил написать свою подсветку кода с блекджеком и шлюхами.
В процессе я столкнулся с непонятыми и недооцененными мной ранее регулярными выражениями, но все мои предрассудки оказались чушью, на деле это самый удобный инструмент для манипуляций текстом которым я когда либо пользовался.
Для примера ниже в спойлере вы найдёте огромный файл кода, который обрабатывается на мой взгляд достаточно быстро, чтобы использовать такую подсветку на стороне клиента.
Куча кода
Если кому то интересно, это здоровенный файл с кодом персонажа из Space Shooter из первого моего поста. Думаю врятли кто то заметил насколько реалистично персонаж держит оружие.
Пользуйтесь наздоровье если что то понравится. Но я не трудился над читабельностью и не думал что кто то когда либо увидит этот код. Я просто схватил самый большой файл, чтобы показать вам подсветку кода.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
[RequireComponent(typeof(CharacterMotor))]
[RequireComponent(typeof(AudioSource))]
public class Player : MonoBehaviour
{
public static string _tag;
public static Player self;
float health;
public float startHealth;
public float Health
{
get { return health; }
set
{
health = value;
GuiManager.self.SetHealth(health / maxHealth);
if (health <= 0)
{
Debug.LogError("Game Over");
Application.Quit();
}
}
}
public float maxHealth;
public Transform _weaponSlot;
CharacterController _characterController;
Transform _camera;
Transform _transform;
CharacterMotor _motor;
AudioSource _audioSource;
public Moving moving;
public Rotation rotation;
public Activity activity;
public Weapons weapons;
public Fotsteps fotsteps;
public WeaponShaking weaponShaking;
bool walk;
int walkState;
WalkState TheWalkState;
bool down;
[HideInInspector]
public Ray forwardRay;
Vector3 cameraRelPos;
void Awake()
{
Init();
self = this;
tag = "Player";
_tag = tag;
moving.SetParent(this);
rotation.SetParent(this);
activity.SetParent(this);
weapons.SetParent(this);
fotsteps.SetParent(this);
weaponShaking.SetParent(this);
}
void Start()
{
Health = startHealth;
}
void Init()
{
_characterController = GetComponent();
if (!_characterController) Debug.LogError("transform is Null");
_camera = Camera.main.transform;
if (!_camera) _camera = Camera.mainCamera.transform;
if (!_camera) Debug.LogError("Camera is Null");
_transform = transform;
if (!_transform) Debug.LogError("transform is Null");
_motor = GetComponent();
if (!_motor) Debug.LogError("CharacterMotor is Null");
if (!_weaponSlot) Debug.LogError("weaponSlot is Null");
_audioSource = GetComponent();
if (!_audioSource) Debug.LogError("audioSource is Null");
// DG = new DebugGraph(0, 0, 200, 100, 100, Color.red, Color.blue);
}
void Update()
{
moving.Update();
rotation.Update();
activity.Update();
weapons.Update();
fotsteps.Update();
weaponShaking.Update();
// DG.Update();
}
void FixedUpdate()
{
weaponShaking.FixedUpdate();
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
if (body == null || body.isKinematic)
return;
if (hit.moveDirection.y < -0.4F)
return;
Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);
body.AddForceAtPosition(pushDir * 20.0F, hit.point);
//body.velocity = pushDir * 2.0F;
}
// DebugGraph DG;
/* void OnGUI()
{
//DG.OnGUI();
}*/
[System.Serializable]
public class Rotation
{
Transform camera;
Transform transform;
public float xMouseSpeed = 5f;
public float yMouseSpeed = 4f;
public float min_X = -60f;
public float max_X = 60f;
Vector3 cameraRotation;
public Rotation(Player parent) { SetParent(parent); }
public void SetParent(Player parent)
{
camera = parent._camera;
transform = parent._transform;
}
public void Update()
{
cameraRotation.x -= Input.GetAxisRaw("Mouse Y") * yMouseSpeed;
float yRotation = Input.GetAxisRaw("Mouse X") * xMouseSpeed;
if (cameraRotation.x < min_X) cameraRotation.x = min_X;
else if (cameraRotation.x > max_X) cameraRotation.x = max_X;
camera.localRotation = Quaternion.Euler(cameraRotation);
transform.Rotate(0, yRotation, 0);
}
}
[System.Serializable]
public class Moving
{
CharacterMotor motor;
Transform transform;
Transform camera;
CharacterController _characterController;
Player player;
Vector3 moveVector;
public float runRatio = 1.7f;
public float creepRatio = 0.4f;
public Moving(Player parent) { SetParent(parent); }
public void SetParent(Player parent)
{
player = parent;
transform = parent._transform;
motor = parent._motor;
_characterController = parent._characterController;
camera = parent._camera;
player.cameraRelPos = camera.localPosition;
}
public void Update()
{
moveVector = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
if (player.down != Input.GetKey(KeyCode.LeftControl))
{
player.down = Input.GetKey(KeyCode.LeftControl);
if (player.down)
{
_characterController.height = 1f;
_characterController.center = new Vector3(0, -0.5f, 0);
camera.localPosition = new Vector3(0, 0, 0);
player.cameraRelPos = camera.localPosition;
}
else
{
Ray ray = new Ray(transform.position, Vector3.up);
if (Physics.Raycast(ray, 1.1f)) player.down = true;
else
{
_characterController.height = 2f;
_characterController.center = new Vector3(0, 0, 0);
camera.localPosition = new Vector3(0, 0.9f, 0);
player.cameraRelPos = camera.localPosition;
}
}
}
if (moveVector != Vector3.zero)
{
moveVector.Normalize();
if (player.down)
{
moveVector *= creepRatio;
player.walkState = 0;
}
else if (Input.GetKey(KeyCode.LeftShift))
{
moveVector *= runRatio;
player.walkState = 2;
}
else player.walkState = 1;
player.walk = true;
}
else player.walk = false;
motor.inputMoveDirection = transform.rotation * moveVector;
motor.inputJump = Input.GetButton("Jump");
}
}
[System.Serializable]
public class Activity
{
Player player;
Transform weaponSlot;
Transform camera;
Transform target;
Info info;
public LayerMask RayCastLayer;
public float castDistance;
[HideInInspector]
public bool enable;
public Activity(Player parent) { SetParent(parent); }
public void SetParent(Player parent)
{
player = parent;
weaponSlot = parent._weaponSlot;
camera = parent._camera;
enable = true;
}
public void Update()
{
if (enable)
{
player.forwardRay = new Ray(camera.position, camera.forward);
Debug.DrawRay(camera.position, camera.forward);
RaycastHit hit;
if (Physics.Raycast(player.forwardRay, out hit, castDistance, RayCastLayer))
{
if (target != hit.transform)
{
target = hit.transform;
info = target.GetComponent();
if (info != null)
GuiManager.self.SetStatus(info.title);
else
GuiManager.self.SetStatus("");
}
if (Input.GetKeyDown(KeyCode.E) && info != null && info.usable) info.U.Use();
}
else
{
if (target != null)
{
target = null;
info = null;
GuiManager.self.SetStatus("");
}
}
Debug.DrawRay(weaponSlot.position, weaponSlot.forward);
}
}
}
[System.Serializable]
public class Weapons
{
Player player;
Transform weaponSlot;
public Weapon[] weapons;
IWeapon selectedWeapon;
int selectedI;
public Weapons(Player parent) { SetParent(parent); }
public void SetParent(Player parent)
{
player = parent;
weaponSlot = parent._weaponSlot;
selectedI = -1;
Select(0);
}
void OnGUI()
{
}
public void Update()
{
SelectUpdate();
}
void SelectUpdate()
{
int i = (int)(Input.GetAxisRaw("ScrollWheel") * 10);
int sign = (i > 0) ? 1 : -1;
if (i != 0)
{
i += selectedI;
if (i < 0) i = 9;
else if (i > 9) i = 0;
int count = 0;
while (!Select(i))
{
i += sign;
if (i < 0) i = 9;
else if (i > 9) i = 0;
count++;
if (count > 20) break;
}
}
if (Input.anyKeyDown)
{
if (Input.GetKeyDown(KeyCode.Alpha1))
Select(0);
else if (Input.GetKeyDown(KeyCode.Alpha2))
Select(1);
else if (Input.GetKeyDown(KeyCode.Alpha3))
Select(2);
else if (Input.GetKeyDown(KeyCode.Alpha4))
Select(3);
else if (Input.GetKeyDown(KeyCode.Alpha5))
Select(4);
else if (Input.GetKeyDown(KeyCode.Alpha6))
Select(5);
else if (Input.GetKeyDown(KeyCode.Alpha7))
Select(6);
else if (Input.GetKeyDown(KeyCode.Alpha8))
Select(7);
else if (Input.GetKeyDown(KeyCode.Alpha9))
Select(8);
else if (Input.GetKeyDown(KeyCode.Alpha0))
Select(9);
}
}
bool Select(int i)
{
if (i < weapons.Length && weapons[i].exist)
{
if (selectedI != i)
{
if (selectedI >= 0) weapons[selectedI].selected = false;
selectedI = i;
weapons[selectedI].selected = true;
GuiManager.self.SetAmmo(weapons[selectedI].weaponAmmo, weapons[selectedI].ammo);
if (weaponSlot.childCount > 0)
{
Transform t = weaponSlot.GetChild(0);
Destroy(t.gameObject);
}
Transform g = ((GameObject)Instantiate(weapons[i].Prefab)).transform;
g.parent = weaponSlot;
g.localPosition = Vector3.zero;
g.localRotation = Quaternion.identity;
selectedWeapon = g.GetComponent();
if (selectedWeapon != null) selectedWeapon.Initialize(weapons[i], player);
}
return true;
}
return false;
}
[System.Serializable]
public class Weapon
{
public Texture tex;
public Texture selectedTex;
public GameObject Prefab;
int id = -1;
[SerializeField]
bool _exist;
public bool exist
{
get { return _exist; }
set
{
if (!_exist && value)
{
_exist = value;
Player.self.weapons.Select(GetId());
}
else
_exist = value;
}
}
int GetId()
{
if (id == -1)
{
Weapon[] w = Player.self.weapons.weapons;
for (int i = 0; i < w.Length; i++)
{
if (w[i] == this)
{
id = i;
return id;
}
}
}
return id;
}
[SerializeField]
int _ammo;
public int maxAmmo;
[SerializeField]
int _weaponAmmo;
public int weaponMaxAmmo;
//[HideInInspector]
public bool selected;
public int weaponAmmo
{
get { return _weaponAmmo; }
set
{
if (_weaponAmmo != value)
{
_weaponAmmo = value;
GuiManager.self.SetAmmo(_weaponAmmo, _ammo);
}
}
}
public int ammo
{
get { return _ammo; }
set
{
if (_ammo != value)
{
_ammo = value;
GuiManager.self.SetAmmo(_weaponAmmo, _ammo);
}
}
}
}
}
[System.Serializable]
public class Fotsteps
{
CharacterController cc;
Transform transform;
AudioSource audioSource;
Player player;
Transform camera;
// Transform weaponSlot;
public AudioClip metalStep;
public float walkDelay;
public float runDelay;
public float creepDelay;
public float firstStepDelay;
public float regress;
public AnimationCurve yAnimation;
public AnimationCurve xAnimation;
public AnimationCurve weaponYAnimation;
float xAFirstFactor;
// Vector3 weaponSlotRelPos;
float nextTime;
float velocity;
bool leftLeg;
public Fotsteps(Player parent) { SetParent(parent); }
public void SetParent(Player parent)
{
player = parent;
transform = parent._transform;
audioSource = parent._audioSource;
cc = parent._characterController;
camera = parent._camera;
xAFirstFactor = xAnimation.keys[0].value * 0.5f;
if (xAFirstFactor < 0) xAFirstFactor = -xAFirstFactor;
}
public void Update()
{
if (player.walk)
{
if (nextTime < Time.time && cc.isGrounded)
{
if (player.TheWalkState == WalkState.stay)
{
player.TheWalkState = WalkState.firstStep;
nextTime = Time.time + firstStepDelay;
}
else
{
if (player.TheWalkState != WalkState.walk) player.TheWalkState = WalkState.walk;
velocity = cc.velocity.magnitude;
audioSource.pitch = Random.value * 0.2f + 0.9f;
audioSource.PlayOneShot(metalStep, velocity * 0.01f);
if (player.walkState == 1) nextTime = Time.time + walkDelay;
else if (player.walkState == 2) nextTime = Time.time + runDelay;
else nextTime = Time.time + creepDelay;
leftLeg = !leftLeg;
}
}
}
else if (player.TheWalkState == WalkState.walk || player.TheWalkState == WalkState.firstStep) player.TheWalkState = WalkState.lastStep;
if (player.TheWalkState == WalkState.stay) return;
float t = nextTime - Time.time;
if (player.TheWalkState == WalkState.lastStep)
{
bool ok = true;
Vector3 vecC = camera.localPosition;
// Vector3 vecW = weaponSlot.localPosition;
vecC.y = Regress(player.cameraRelPos.y, camera.localPosition.y, ref ok);
vecC.x = Regress(player.cameraRelPos.x, camera.localPosition.x, ref ok);
//vecW.y = Regress(weaponSlotRelPos.y, weaponSlot.localPosition.y, ref ok);
// weaponSlot.localPosition = vecW;
camera.localPosition = vecC;
if (ok) { player.TheWalkState = WalkState.stay; leftLeg = false; }
}
else//first step and walk
{
if (player.TheWalkState == WalkState.firstStep) t /= firstStepDelay;
else if (player.walkState == 1) t /= walkDelay;
else if (player.walkState == 2) t /= runDelay;
else t /= creepDelay;
t = 1 - t;
if (t > 1 || t < 0) t = 0;
float ty = yAnimation.Evaluate(t);
float tx = xAnimation.Evaluate(t);
float wy = weaponYAnimation.Evaluate(t);
if (leftLeg) tx = -tx;
if (player.TheWalkState == WalkState.firstStep)
{
ty *= 0.5f;
tx = (tx * 0.5f) + xAFirstFactor;
wy *= t;
}
//weaponSlot.localPosition = weaponSlotRelPos + new Vector3(0, wy, 0) * velocity * 0.1f;
camera.localPosition = player.cameraRelPos + new Vector3(tx, ty, 0) * velocity * 0.1f;
}
}
float Regress(float constPos, float localPos, ref bool ok)
{
float vy = localPos - constPos;
if (vy > 0)
{
if (vy < regress) localPos = constPos;
else { localPos -= regress; ok = false; }
}
else if (vy < 0)
{
if (-vy < regress) { localPos = constPos; }
else { localPos += regress; ok = false; }
}
return localPos;
}
}
[System.Serializable]
public class Shaking
{
Transform transform;
Transform camera;
Transform weaponSlot;
Player player;
Vector3 cameraLastPos;
Vector3 transformLastPos;
Vector3 weaponSlotRelPos;
Vector3 weaponSlotRelRot;
float mouseSmoothX;
float mouseSmoothY;
public float axeleration;
public float regressVel;
public float regressFactor;
public float limitVel;
public float limitAx;
public float treshold;
public Shaking(Player parent) { SetParent(parent); }
public void SetParent(Player parent)
{
player = parent;
transform = parent._transform;
camera = parent._camera;
weaponSlot = parent._weaponSlot;
weaponSlotRelPos = weaponSlot.localPosition;
weaponSlotRelRot = weaponSlot.localEulerAngles;
breathingY.postWrapMode = WrapMode.Loop;
graph = new DebugGraph(0, 0, 200, 100, 0.000000001f);
graph.vals = new DebugGraph.Value[2];
graph.vals[0] = new DebugGraph.Value(Color.red);
graph.vals[1] = new DebugGraph.Value(Color.blue);
}
public DebugGraph graph;
public float graphScale;
public Smooth cam_X;
public Smooth cam_Y;
float impulseYCam;
float impilseYTr;
public float impYF;
public float impYR;
public float wepYLim;
public AnimationCurve breathingY;
public float breathDelay;
public MyRandom random;
public void Update()
{
Vector3 trVel = transform.InverseTransformDirection(transform.position - transformLastPos);
Vector3 camVel = camera.localPosition - cameraLastPos;
transformLastPos = transform.position;
cameraLastPos = camera.localPosition;
float camX = camera.localEulerAngles.x;
if (camX > 180) camX -= 360f;
float dx = Input.GetAxis("Mouse X");
float dy = Input.GetAxis("Mouse Y");
dx = Double(dx);
dy = Double(dy);
mouseSmoothX += trVel.x * 0.009f;
mouseSmoothX = Smooth(mouseSmoothX, dx);
mouseSmoothY -= trVel.z * 0.01f;
mouseSmoothY = Smooth(mouseSmoothY, dy);
ImpulseY(trVel, camVel);
float breathTime = Time.time * breathDelay;
Vector3 r = random.Get();
Vector3 RotDelta = new Vector3(-mouseSmoothY * 100f, mouseSmoothX * -200f, mouseSmoothX * -500f);
RotDelta.x += camX * 0.05f;
RotDelta.x -= -breathingY.Evaluate(breathTime - 0.1f) * 90f;
RotDelta.x += r.z * 200f;
Vector3 PosDelta = new Vector3(cam_X.GetSmooth(camVel.x), camX * -0.0004f, 0);
PosDelta.x += r.x;
PosDelta.y += impulseYCam + impilseYTr;
PosDelta.y += breathingY.Evaluate(breathTime);
PosDelta.y += r.y;
if (player.walkState == 2 && player.TheWalkState == WalkState.walk)
{
if (runRot > -60)
{
runRot -= 5f;
}
}
else
{
if (runRot < 0)
{
runRot += 5f;
}
}
RotDelta.y += runRot;
PosDelta.z += runRot * 0.002f;
weaponSlot.localEulerAngles = weaponSlotRelRot + RotDelta;
weaponSlot.localPosition = weaponSlotRelPos + PosDelta;
graph.vals[1].val = PosDelta.y;
graph.vals[0].val = camVel.y;
graph.scale = graphScale;
graph.Update();
}
float runRot;
void ImpulseY(Vector3 trVel, Vector3 camVel)
{
impilseYTr += trVel.y * 0.02f;
impilseYTr *= 0.9f;
impulseYCam += cam_Y.GetSmooth(camVel.y * 0.5f);
impulseYCam *= impYF;
impulseYCam = Limit(impulseYCam, wepYLim);
if (player.TheWalkState == WalkState.lastStep || player.TheWalkState == WalkState.stay)//чтобы быстрее вернуть оружие в изначальное положение
impulseYCam = Regress(impulseYCam, 0.002f);
else
impulseYCam = Regress(impulseYCam, impYR);
}
float Double(float val)
{
if (val > 0) return val * val;
else return val * -val;
}
float Smooth(float velocity, float delta)
{
delta -= velocity;
delta = Limit(delta, limitAx);
velocity += (velocity + delta) * axeleration;
if (velocity > treshold || velocity < -treshold) velocity *= regressFactor;
else velocity = Regress(velocity, regressVel);
return Limit(velocity, limitVel);
}
float Smooth(float velocity, float delta, float limit_Ax, float limit_Vel, float tresh, float axeleration)
{
delta -= velocity;
delta = Limit(delta, limit_Ax);
velocity += (velocity + delta) * axeleration;
if (velocity > tresh || velocity < -tresh) velocity *= regressFactor;
else velocity = Regress(velocity, regressVel);
return Limit(velocity, limit_Vel);
}
}
[System.Serializable]
public class WeaponShaking
{
Transform transform;
Transform camera;
Transform weaponSlot;
Player player;
Vector3 WeaponDefaultPos;
Vector3 WeaponDeltaPos;
Vector3 WeaponVelocity;
Vector3 WeaponAcceleration;
Vector3 WeaponDefaultRot;
Vector3 WeaponDeltaRot;
Vector3 WeaponRotVelocity;
Vector3 WeaponRotAcceleration;
public float recoverySpeed;
public float fallVelocity;
public float fallRotVelocity;
public Vector3 TrImpulseFactor;
public Vector3 CamImpulseFactor;
public float trIncrease;
public float camIncrease;
public float CamSmoothGrain;
public float CamSmoothFall;
public WeaponShaking(Player parent) { SetParent(parent); }
public void SetParent(Player parent)
{
player = parent;
transform = parent._transform;
camera = parent._camera;
weaponSlot = parent._weaponSlot;
WeaponDefaultPos = weaponSlot.localPosition;
WeaponDefaultRot = weaponSlot.localEulerAngles;
breathingY.postWrapMode = WrapMode.Loop;
cameraLastPos = camera.localPosition;
transformLastPos = transform.position;
TrImpulseFactor *= trIncrease;
CamImpulseFactor *= camIncrease;
}
Vector3 transformLastPos;
Vector3 transformLastVel;
Vector3 transformAx;
Vector3 cameraLastPos;
Vector3 cameraLastVel;
Vector3 cameraAx;
Vector3 cameraAxL;
bool lastDown;
float kickImpulse;
public void Kick(float impulse)
{
kickImpulse += impulse;
}
public void FixedUpdate()
{
Vector3 trVel = transform.InverseTransformDirection(transform.position - transformLastPos);
transformLastPos = transform.position;
transformAx = trVel - transformLastVel;
transformLastVel = trVel;
}
public void Update()
{
WeaponAcceleration = -WeaponDeltaPos * recoverySpeed * Time.deltaTime;
WeaponRotAcceleration = -WeaponDeltaRot * recoverySpeed * Time.deltaTime;
if (player.down != lastDown)
{
cameraLastPos = player.cameraRelPos;
lastDown = player.down;
}
Vector3 camVel = camera.localPosition - cameraLastPos;
cameraLastPos = camera.localPosition;
cameraAx += (camVel - cameraLastVel) * CamSmoothGrain;
cameraAx *= CamSmoothFall;
cameraLastVel = camVel;
if (kickImpulse != 0f)
{
WeaponRotAcceleration.x -= kickImpulse;
WeaponAcceleration.y += kickImpulse*0.001f;
kickImpulse = 0f;
}
Composition();
Breathing();
WeaponVelocity += WeaponAcceleration;
WeaponVelocity *= fallVelocity;
WeaponDeltaPos += WeaponVelocity;
weaponSlot.localPosition = WeaponDefaultPos + WeaponDeltaPos + new Vector3(0, -camX * 0.0001f, 0);
WeaponRotVelocity += WeaponRotAcceleration;
WeaponRotVelocity *= fallRotVelocity;
WeaponDeltaRot += WeaponRotVelocity;
weaponSlot.localEulerAngles = WeaponDefaultRot + WeaponDeltaRot + new Vector3(camX * 0.01f, 0, 0);
}
float camX;
void Composition()
{
transformAx.Scale(TrImpulseFactor);
WeaponAcceleration += new Vector3(-transformAx.x + cameraAx.x * CamImpulseFactor.x, -transformAx.y + cameraAx.y * CamImpulseFactor.y, -transformAx.z);
camX = camera.localEulerAngles.x;
if (camX > 180) camX -= 360f;
float dx = Input.GetAxis("Mouse X");
float dy = Input.GetAxis("Mouse Y");
float xIncrease = dx * 0.1f + transformLastVel.x;
xIncrease = Limit(xIncrease, 0.04f);
WeaponRotAcceleration.z -= xIncrease;
WeaponRotAcceleration.y -= xIncrease * 0.05f;
WeaponRotAcceleration.x += -dy * 0.02f + transformAx.y * 150f;
}
public MyRandom rnd;
public AnimationCurve breathingY;
public float breathDelay;
public float breathScale;
void Breathing()
{
float breathTime = Time.time * breathDelay;
WeaponAcceleration.y += breathingY.Evaluate(breathTime) * breathScale;
WeaponAcceleration += rnd.Get();
}
}
static float Limit(float val, float limit)
{
if (val > limit) val = limit;
else if (val < -limit) val = -limit;
return val;
}
static float Regress(float localPos, float regress)
{
if (localPos > 0)
{
if (localPos < regress) localPos = 0f;
else localPos -= regress;
}
else if (localPos < 0)
{
if (-localPos < regress) localPos = 0f;
else localPos += regress;
}
return localPos;
}
}
[System.Serializable]
public class MyRandom
{
Vector3 vel;
Vector3 pos;
float nextTime;
public float freq;
public float minValTime;
public float scale;
public float center;
public Vector3 Get()
{
if (nextTime < Time.time)
{
vel = -pos * center * Time.deltaTime + Random.insideUnitSphere * scale;
nextTime = Time.time + Random.value * freq + minValTime;
}
pos += vel;
return pos;
}
}
public class DebugGraph
{
Texture2D tex;
int t;
public float scale;
int h;
int ch;
int w;
public Rect rect;
public Value[] vals;
public DebugGraph(int x, int y, int width, int height, float scale, params Color[] colors) : this(new Rect(x, y, width, height), scale, colors) { }
public DebugGraph(Rect rect, float scale, params Color[] colors)
{
this.rect = rect;
h = (int)rect.height;
w = (int)rect.width;
ch = (int)(rect.height / 2f);
this.scale = scale;
tex = new Texture2D((int)rect.width, (int)rect.height);
if (colors.Length == 0) return;
vals = new Value[colors.Length];
for (int i = 0; i < vals.Length; i++)
{
vals[i] = new Value(colors[i]);
}
}
int Val(float value)
{
int v = (int)(value * scale) + ch;
if (v >= h) v = h - 1;
if (v < 0) v = 0;
return v;
}
public void Update()
{
Color[] cols = new Color[h];
for (int i = 0; i < h; i++) cols[i] = Color.white;
cols[ch] = Color.black;
for (int i = 0; i < vals.Length; i++) vals[i].Drawe(cols, this);
tex.SetPixels(t, 0, 1, h, cols);
tex.Apply();
t++;
if (t >= w) t = 0;
}
public void OnGUI()
{
GUI.DrawTexture(rect, tex);
}
public class Value
{
public Color color;
public float val;
int lastVal;
public Value(Color color)
{
this.color = color;
}
public void Drawe(Color[] colors,DebugGraph G)
{
int ival = G.Val(val);
int start;
int end;
if (ival > lastVal) { start = lastVal; end = ival; }
else { start = ival; end = lastVal; }
for (int i = start; i <= end; i++)
{
colors[i] = color;
}
lastVal = ival;
}
}
}
[System.Serializable]
public class Smooth
{
float velocity;
public float axeleration;
public float limitAxeleration;
public float treshold;
public float regressFactor;
public float regressVelocity;
public float limitVelocity;
public float GetSmooth(float delta)
{
delta -= velocity;
delta = Limit(delta, limitAxeleration);
velocity += (velocity + delta) * axeleration;
if (velocity > treshold || velocity < -treshold) velocity *= regressFactor;
else velocity = Regress(velocity, regressVelocity);
velocity = Limit(velocity, limitVelocity);
return velocity;
}
public static float Limit(float val, float limit)
{
if (val > limit) val = limit;
else if (val < -limit) val = -limit;
return val;
}
public static float Regress(float localPos, float regress)
{
if (localPos > 0)
{
if (localPos < regress) localPos = 0f;
else localPos -= regress;
}
else if (localPos < 0)
{
if (-localPos < regress) localPos = 0f;
else localPos += regress;
}
return localPos;
}
}
public enum WalkState
{
firstStep,
walk,
lastStep,
stay
}
Пользуйтесь наздоровье если что то понравится. Но я не трудился над читабельностью и не думал что кто то когда либо увидит этот код. Я просто схватил самый большой файл, чтобы показать вам подсветку кода.
Всё что вам нужно сделать это включить js и css файлы из архива вставить код в тег xmp и присвоить ему класс csharp
Комментариев нет:
Отправить комментарий