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

Программирование на Юнити.

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

Сообщение h1kkvl 11 окт 2022, 19:04

Здравствуйте у меня возникла проблема в скрипте я думаю, когда я перемещаюсь у меня модель персонажа очень сильно трясёт.
Вот Скрипт:

public List<AudioSource> sounds;
public Animator anim;
public Rigidbody rig;
public Transform mainCamera;

[Header ("Pause")]
[SerializeField] private GameObject pausePanel;
private bool escOpened;
public GameObject UIBG;
public GameObject crosshair;
public CinemachineVirtualCamera CVC;


public float jumpForce = 3.5f;
public float walkingSpeed = 2f;
public float runningSpeed = 6f;
public float swimmingSpeed = 1.5f;
public float currentSpeed;
private float animationInterpolation = 1f;


public InventoryManager inventoryManager;
public QuickslotInventory quickslotInventory;
public CraftManager craftManager;
public Indicators indicators;
public SwordDamage swordDamage;
public EnemyScript enemyScript;

public Transform aimTarget;
public Transform hitTarget;
public Vector3 hitTargetOffset;

[SerializeField] private bool isOpened;
[SerializeField] private List<GameObject> hud;
public bool isNeckUnderWater;


[Header ("Ground Detection")]
[SerializeField] private Transform groundCheck;
[SerializeField] float groundRadius;
[SerializeField] LayerMask whatIsGround;
[SerializeField] bool isGround;


[SerializeField] private Transform _neckObj;
[SerializeField] private float _waterLevel = -1;

[SerializeField] private Transform _groundObj;

void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}

bool isGrounded() => Physics.Raycast(_groundObj.position, Vector3.down, 0.1f, LayerMask.GetMask("Default","Terrain"));

bool IsSwimming()
{
isNeckUnderWater = _waterLevel > _neckObj.position.y;

if (isGrounded() && !isNeckUnderWater)
{
return false;
}
else if (isGrounded() && isNeckUnderWater)
{
return true;
}
else if (!isGrounded() && isNeckUnderWater)
{
return true;
}

return false;
}

void Run()
{
animationInterpolation = Mathf.Lerp(animationInterpolation, 1.5f, Time.deltaTime * 3);
anim.SetFloat("x", Input.GetAxis("Horizontal") * animationInterpolation);
anim.SetFloat("y", Input.GetAxis("Vertical") * animationInterpolation);

currentSpeed = Mathf.Lerp(currentSpeed, runningSpeed, Time.deltaTime * 3);
}
void Walk()
{
animationInterpolation = Mathf.Lerp(animationInterpolation, 1f, Time.deltaTime * 3);
anim.SetFloat("x", Input.GetAxis("Horizontal") * animationInterpolation);
anim.SetFloat("y", Input.GetAxis("Vertical") * animationInterpolation);

currentSpeed = Mathf.Lerp(currentSpeed, walkingSpeed, Time.deltaTime * 3);
}

void Swim()
{
animationInterpolation = Mathf.Lerp(animationInterpolation, 1f, Time.deltaTime * 3);
anim.SetFloat("x", Input.GetAxis("Horizontal") * animationInterpolation);
anim.SetFloat("y", Input.GetAxis("Vertical") * animationInterpolation);

currentSpeed = Mathf.Lerp(currentSpeed, swimmingSpeed, Time.deltaTime * 3);
}

void Die()
{
if(indicators.healthAmount < 0)
{
Destroy(gameObject);
}
}

void PauseMenu()
{
pausePanel.SetActive(false);
}


public void ChangeLayerWeight(float newLayerWeight)
{
StartCoroutine(SmoothLayerWeightChange(anim.GetLayerWeight(1), newLayerWeight, 0.3f));
}

IEnumerator SmoothLayerWeightChange(float oldWeight, float newWeight, float changeDuration)
{
float elapsed = 0f;
while(elapsed < changeDuration)
{
float currentWeight = Mathf.Lerp(oldWeight, newWeight, elapsed / changeDuration);
anim.SetLayerWeight(1, currentWeight);
elapsed += Time.deltaTime;
yield return null;
}
anim.SetLayerWeight(1, newWeight);
}

private void Update()
{
OffHud();
// Устанавливаем поворот персонажа когда камера поворачивается
transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x,mainCamera.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);
if (IsSwimming())
{
rig.useGravity = false;
Swim();
anim.SetBool("Swimming",true);
}
else
{
rig.useGravity = true;
if (Input.GetKeyDown(KeyCode.Mouse0))
{
if (quickslotInventory.activeSlot != null)
{
if (quickslotInventory.activeSlot.item != null)
{
if (quickslotInventory.activeSlot.item.itemType == ItemType.Instrument)
{
if (inventoryManager.isOpened == false && craftManager.isOpened == false)
{
anim.SetBool("Hit", true);
}
}
}
}
}

if (Input.GetKeyUp(KeyCode.Mouse0))
{
anim.SetBool("Hit", false);
}

if (Input.GetKeyDown(KeyCode.Mouse0))
{
if (quickslotInventory.activeSlot != null)
{
if (quickslotInventory.activeSlot.item != null)
{
if (quickslotInventory.activeSlot.item.itemType == ItemType.Weapon)
{
if (inventoryManager.isOpened == false && craftManager.isOpened == false)
{
anim.SetBool("Attack",true);
swordDamage.trigger.SetActive(true);
}
}
}
}
}

if (Input.GetKeyUp(KeyCode.Mouse0))
{
anim.SetBool("Attack", false);
swordDamage.trigger.SetActive(false);
}

Die();

// Зажаты ли кнопки W и Shift?
if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.LeftShift))
{
// Зажаты ли еще кнопки A S D?
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D))
{
// Если да, то мы идем пешком
Walk();
}
// Если нет, то тогда бежим!
else
{
Run();
}
}
// Если W & Shift не зажаты, то мы просто идем пешком
else
{
Walk();
}

//Если зажат пробел, то прыжок
isGround = Physics.CheckSphere(groundCheck.position, groundRadius, (int)whatIsGround);
if(Input.GetKeyDown(KeyCode.Space) && isGround)
{
Jump();
anim.SetBool("Jump", true);
sounds[0].Play();
}
}

if(Input.GetKeyDown(KeyCode.Escape))
{
escOpened = !escOpened;
pausePanel.SetActive(true);
if(escOpened)
{
pausePanel.SetActive(true);
UIBG.SetActive(true);
crosshair.SetActive(false);

CVC.GetCinemachineComponent<CinemachinePOV>().m_HorizontalAxis.m_InputAxisName = "";
CVC.GetCinemachineComponent<CinemachinePOV>().m_VerticalAxis.m_InputAxisName = "";
CVC.GetCinemachineComponent<CinemachinePOV>().m_HorizontalAxis.m_InputAxisValue = 0;
CVC.GetCinemachineComponent<CinemachinePOV>().m_VerticalAxis.m_InputAxisValue = 0;
// Прекрепляем курсор к середине экрана
Cursor.lockState = CursorLockMode.None;
// и делаем его невидимым
Cursor.visible = true;
Time.timeScale = 0f;
}
else
{
pausePanel.SetActive(false);
UIBG.SetActive(false);
crosshair.SetActive(true);

CVC.GetCinemachineComponent<CinemachinePOV>().m_HorizontalAxis.m_InputAxisName = "Mouse X";
CVC.GetCinemachineComponent<CinemachinePOV>().m_VerticalAxis.m_InputAxisName = "Mouse Y";
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
Time.timeScale = 1f;
}
}

Ray desiredTargetRay = mainCamera.GetComponent<Camera>()
.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2));
Vector3 desiredTargetPosition =
desiredTargetRay.origin + desiredTargetRay.direction * 1.5f; // changed from 0.7 to 1.5
aimTarget.position = desiredTargetPosition;
//hitTarget.position = new Vector3(desiredTargetPosition.x + hitTargetOffset.x, desiredTargetPosition.y + hitTargetOffset.y, desiredTargetPosition.z + hitTargetOffset.z);

}

// Update is called once per frame
void FixedUpdate()
{
// Здесь мы задаем движение персонажа в зависимости от направления в которое смотрит камера
// Сохраняем направление вперед и вправо от камеры
Vector3 camF = mainCamera.forward;
Vector3 camR = mainCamera.right;
camF.y = 0;
camR.y = 0;
// Чтобы направления вперед и вправо не зависили от того смотрит ли камера вверх или вниз, иначе когда мы смотрим вперед, персонаж будет идти быстрее чем когда смотрит вверх или вниз
// Можете сами проверить что будет убрав camF.y = 0 и camR.y = 0 :)

Vector3 movingVector;
if (IsSwimming())
{
movingVector =
Vector3.ClampMagnitude(
camF.normalized * Input.GetAxis("Vertical") * currentSpeed +
camR.normalized * Input.GetAxis("Horizontal") * currentSpeed, currentSpeed);
Debug.DrawRay(mainCamera.position, movingVector, Color.blue);
}
else
{
// Тут мы умножаем наше нажатие на кнопки W & S на направление камеры вперед и прибавляем к нажатиям на кнопки A & D и умножаем на направление камеры вправо
movingVector =
Vector3.ClampMagnitude(
camF.normalized * Input.GetAxis("Vertical") * currentSpeed +
camR.normalized * Input.GetAxis("Horizontal") * currentSpeed, currentSpeed);
}
// Magnitude - это длинна вектора. я делю длинну на currentSpeed так как мы умножаем этот вектор на currentSpeed на 86 строке. Я хочу получить число максимум 1.
anim.SetFloat("magnitude", movingVector.magnitude / currentSpeed);
// Здесь мы двигаем персонажа! Устанавливаем движение только по x & z потому что мы не хотим чтобы наш персонаж взлетал в воздух
rig.velocity = new Vector3(movingVector.x, rig.velocity.y, movingVector.z);
rig.angularVelocity = Vector3.zero;
}
h1kkvl
UNец
 
Сообщения: 3
Зарегистрирован: 29 авг 2022, 04:44

Вернуться в Скрипты

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 12