Advertisement
torch_in_sky

Simple snake controller

Apr 15th, 2020
654
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class SnakeControllerTest : MonoBehaviour
  6. {
  7.     [SerializeField] private List<Transform> _bodyParts;
  8.     [SerializeField] private float _distanceBetwenParts = 1f;
  9.     [SerializeField] private float _movementSpeed = 1f;
  10.     [SerializeField] private float _turningSpeed = 90f;
  11.    
  12.     private List<Vector3> _positions;
  13.  
  14.     private void Start()
  15.     {
  16.         for (int i = 0; i < _bodyParts.Count; i++)
  17.         {
  18.             _positions.Add(_bodyParts[i].position);
  19.         }
  20.     }
  21.  
  22.     private void Update()
  23.     {
  24.         HandleInput();
  25.         HandleSnakeMovement();
  26.     }
  27.  
  28.     private void HandleInput()
  29.     {
  30.         transform.Rotate(Vector3.up, Input.GetAxis("Horizontal") * _turningSpeed * Time.deltaTime);
  31.     }
  32.  
  33.     private void HandleSnakeMovement()
  34.     {
  35.         _bodyParts[0].Translate(_bodyParts[0].forward * _movementSpeed * Time.deltaTime, Space.World);
  36.         float distance = Vector3.Distance(_bodyParts[0].position, _positions[0]);
  37.        
  38.         if (distance > _distanceBetwenParts)
  39.         {
  40.             Vector3 direction = (_bodyParts[0].position - _positions[0]).normalized;
  41.             Vector3 newPos = _positions[0] + direction * _distanceBetwenParts;
  42.             _positions.Insert(0, newPos);
  43.             _positions.RemoveAt(_positions.Count - 1);
  44.             distance = Vector3.Distance(_bodyParts[0].position, _positions[0]);
  45.         }
  46.  
  47.         float lerpProgress = distance / _distanceBetwenParts;
  48.  
  49.         for (int i = 1; i < _bodyParts.Count; i++)
  50.         {
  51.             _bodyParts[i].position = Vector3.Lerp(_positions[i], _positions[i - 1], lerpProgress);
  52.             var dir = (_bodyParts[i - 1].position - _bodyParts[i].position).normalized;
  53.             _bodyParts[i].rotation = Quaternion.LookRotation(dir);
  54.         }
  55.     }
  56. }
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement