Unity 3D Рух по лініям

2075 / Unity / 3D / Додатково / Рух по лініям

 

public float firstLanePos = 1.5f;
public float laneDistance = -1.5f;
public float sideSpeed = 5f;
float speed = 5f;
int laneNumber = 1;
int lanesCount = 2; // лінії 0, 1, 2
bool didChangeLastFrame = false;

void Update()
{
  float input = Input.GetAxis("Horizontal");

  if (Mathf.Abs(input) > 0.1f)
  {
    if (!didChangeLastFrame)
    {
      didChangeLastFrame = true;
      laneNumber += (int)Mathf.Sign(input);
      laneNumber = Mathf.Clamp(laneNumber, 0, lanesCount);
    }
  }
  else 
  {
    didChangeLastFrame = false;
  }

  Vector3 newPos = transform.position;
  newPos.z = Mathf.Lerp(newPos.z, firstLanePos + (laneNumber * laneDistance), Time.deltaTime * sideSpeed);
  transform.position = newPos;
}