I am making a game that contains several tracks, a player car and each track is labeled with a specific button on the keyboard. I know how to change the position of the car from one track to the other but is there a way to make the car move gradually from one track to the other (like a normal car does), instead of instantly changing its position to another track?
For example, the tracks are labeled with “A”, “S”, “D”, when I press “A” on the keyboard, the car instantly switch its position to track “A” but I would like it to be moving from the current track gradually to the “A” track.
I know you said you tried “moveTowards” but I gave it shot and this code is working pretty smooth for me. i attached it to my “car” gameObject. I tested this in 2D which is why i used a Vector2.MoveTowards(, just change to vector 3 if youre doing a 3d game.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JustTesting : MonoBehaviour
{
public Transform road1, road2, road3, road4;
public float speed = 1;
public string temp;
// Start is called before the first frame update
void Update()
{
Switch();
if (Input.GetKey (KeyCode.A))
{
temp = "3";
}
if (Input.GetKey(KeyCode.S))
{
temp = "32";
}
if (Input.GetKey(KeyCode.D))
{
temp = "34";
}
if (Input.GetKey(KeyCode.W))
{
temp = "35";
}
}
// Update is called once per frame
void Switch()
{
Vector3 move;
float step = speed * Time.deltaTime;
switch (temp)
{
case "3":
Debug.Log("30");
move = Vector2.MoveTowards(transform.position, road1.position, step);
transform.position = move;
break;
case "32":
Debug.Log("32");
move = Vector2.MoveTowards(transform.position, road2.position, step);
transform.position = move;
break;
case "34":
Debug.Log("34");
move = Vector2.MoveTowards(transform.position, road3.position, step);
transform.position = move;
break;
case "35":
Debug.Log("35");
//move = road4.position;
//transform.position = move;
break;
default:
Debug.Log("NO INPUT");
break;
}
}
}