Hello everyone,
I want to move a car on a box collider, but the car does not flip upside down when turning in the opposite direction. How can I solve this issue? Below, I’m uploading my code and images showing the car’s movements step by step:
[SerializeField] private Vector3[] corners = new Vector3[4];
[SerializeField] private float Speed;
[SerializeField] private float rotateSpeed;
private int currentCornerIndex;
[SerializeField] private GameObject obj;
Vector3 CubeSize;
Vector3 CubeOrigin;
private void Start()
{
CubeOrigin = obj.transform.position;
CubeSize = obj.GetComponent<BoxCollider>().bounds.size;
corners[0] = CubeOrigin + new Vector3(CubeSize.x / 2, CubeSize.y / 2, 0);
corners[1] = CubeOrigin + new Vector3(-CubeSize.x / 2, CubeSize.y / 2, 0);
corners[2] = CubeOrigin + new Vector3(-CubeSize.x / 2, -CubeSize.y / 2, 0);
corners[3] = CubeOrigin + new Vector3(CubeSize.x / 2, -CubeSize.y / 2, 0);
/* Test
foreach (Vector3 transform in corners)
{
GameObject obj = new GameObject("Corner");
obj.transform.position = transform;
}
*/
Debug.Log($"{corners[0]} ,{corners[1]}, {corners[2]}, {corners[3]},");
}
private void Update()
{
Vector3 targetPos = corners[currentCornerIndex];
transform.position = Vector3.MoveTowards(transform.position, targetPos, Speed * Time.deltaTime);
if (Vector3.Distance(transform.position, targetPos) <= 0.1f)
{
currentCornerIndex = (currentCornerIndex + 1) % corners.Length;
}
//Rotation
Vector3 direction = (targetPos - transform.position).normalized;
if (direction != Vector3.zero)
{
Quaternion rotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Lerp(transform.rotation, rotation, rotateSpeed * Time.deltaTime);
}
}