начальные настройки для объяснения моего кода
у меня не та ось, которую вы используете ..
в середине дороги, значение X для автомобиля равно -5, -7,5 для левой стороны и -2,5 для правой стороны
проблема, которую необходимо решить: Когда вы нажимаете левую клавишу, автомобиль едет влево, и когда клавиша отпущена, цель состоит в том, чтобы автоматически go вперед на x = -5 для автомобиля .. и не забудьте сбросить вращение Y на 0
этот код может быть оптимизирован, но его функционал
Другой подход будет состоять в том, чтобы использовать Path с агентом navme sh, но и другой код тоже
using System.Collections.Generic;
using UnityEngine;
public class CarController : MonoBehaviour
{
private enum Direction { Left = -1, Middle, Right };
private Rigidbody rgb;
public float moveSpeed = 10.0f;
public float rotation_speed = 10f;
public float rotation, currentRotation;
public Vector3 currentPosition;
private Direction currentDirection, lastDirection;
private bool returnToMiddle;
private float middlePositionX;
public GameObject PieceOfRoad;
private Queue<GameObject> PiecesOfRoad = new Queue<GameObject>();
void Start()
{
lastDirection = Direction.Middle;
returnToMiddle = false;
rgb = GetComponent<Rigidbody>();
//initialize the initial middle position X of the car
middlePositionX = rgb.position.x;
// Load 4 pieces of road
for (int i = 0; i < 4; i++)
PiecesOfRoad.Enqueue(Instantiate(PieceOfRoad, new Vector3(0f, 0f, i * 50f), Quaternion.identity));
}
// Update is called once per frame
void Update()
{
currentPosition = rgb.position;
// Destroy the first piece of road of the Queue and create a new piece of road
var z = PiecesOfRoad.Peek().transform.position.z;
if (currentPosition.z > z + 50)
{
Destroy(PiecesOfRoad.Dequeue());
PiecesOfRoad.Enqueue(Instantiate(PieceOfRoad, new Vector3(0f, 0f, z + 200f), Quaternion.identity));
}
//
rotation = Input.GetAxisRaw("Horizontal");
if (rotation < 0)
currentDirection = Direction.Left;
else if (rotation > 0)
currentDirection = Direction.Right;
else
currentDirection = Direction.Middle;
// replace +transform.forward following your axis
rgb.MovePosition(rgb.position + transform.forward * moveSpeed * Time.fixedDeltaTime);
// the return to middle is on but we press a new key
if (returnToMiddle && currentDirection != Direction.Middle)
{
returnToMiddle = false;
}
// we have released key so return to middle is activated
if (returnToMiddle && currentDirection == Direction.Middle)
{
// you could adjust the sensibility by increasing or decreasing the values (0.5f, 1.0f)
if (lastDirection == Direction.Left && currentPosition.x > middlePositionX - 0.5f ||
lastDirection == Direction.Right && currentPosition.x < middlePositionX + 1.0f)
{
rgb.transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0f, 0f, 0f),
5.0f * Time.deltaTime);
currentRotation = rgb.transform.rotation.y;
if (currentRotation < 0.01f) // if rotation is near 0, stop the autmatism
returnToMiddle = false;
}
else
{
CalculusNewRotation(-(int)lastDirection);
}
return;
}
if (currentDirection == Direction.Middle && !returnToMiddle)
{
if (lastDirection == Direction.Middle)
{
returnToMiddle = false;
CalculusNewRotation(rotation);
}
else
{
returnToMiddle = true;
}
return;
}
if (currentDirection != Direction.Middle)
{
lastDirection = currentDirection;
returnToMiddle = false;
CalculusNewRotation(rotation);
}
void CalculusNewRotation(float rotation)
{
Vector3 yrot = Vector3.up * rotation * rotation_speed * Time.deltaTime;
Quaternion deltaRot = Quaternion.Euler(yrot);
Quaternion targetRot = rgb.rotation * deltaRot;
rgb.MoveRotation(Quaternion.Slerp(rgb.rotation, targetRot, 50f * Time.fixedDeltaTime));
}
}
}
Хорошая игра !!