Enter/Exit Vehicle in 2D top down view
Hello I am trying to make a game similar to gta 1 or 2 .. where you have top down view and you can drive any vehicle.... but I ran in to a problem...
I made a script for entering or exiting vehicle.. script is attached to vehicle. And Vehicle (in this case tractor) has 2 colliders, 1 is for rigidbody and other is for player entering car, which is trigger. Problem is that camera doesn't get to 0,0,-10 everytime.. and when you press E it enters/exits several times, Here is my script:
public int movementSpeed = 2;
public int rotationSpeed = 50;
static float angle = 0;
GameObject camera1;
GameObject player;
GameObject tractor1;
bool isInVehicle;
bool isInCollider;
Vector3 tractorPosition;
//private Vector3 pos;
void Start () {
isInVehicle = false;
}
void Update () {
if (isInVehicle) {
if (Input.GetKey (KeyCode.W)) {
transform.Translate (Vector3.up * movementSpeed * Time.deltaTime);
}
if (Input.GetKey (KeyCode.S)) {
transform.Translate (Vector3.down * movementSpeed * Time.deltaTime);
}
if (Input.GetKey (KeyCode.A)) {
angle = angle + rotationSpeed * Time.deltaTime;
}
if (Input.GetKey (KeyCode.D)) {
angle = angle - rotationSpeed * Time.deltaTime;
}
transform.rotation = Quaternion.Euler (new Vector3 (0f, 0f, angle));
}
if (Input.GetKey (KeyCode.Escape)) {
Application.LoadLevel(0);
}
if (Input.GetKey (KeyCode.E)) {
if (isInCollider) {
Debug.Log ("Key pressed...");
camera1 = GameObject.FindWithTag ("MainCamera");
player = GameObject.FindWithTag ("player");
tractor1 = GameObject.FindWithTag ("tractor1");
tractorPosition = transform.position;
if (!isInVehicle) {
Debug.Log ("Entered vehicle..");
camera1.transform.parent = tractor1.transform;
player.GetComponent<Renderer> ().enabled = false;
isInVehicle = true;
} else {
Debug.Log ("In vehicle....");
if (isInVehicle) {
Debug.Log ("Exited vehicle....");
camera1.transform.parent = player.transform;
player.GetComponent<Renderer> ().enabled = true;
player.transform.position = tractorPosition;
isInVehicle = false;
}
}
camera1.transform.position = new Vector3 (0f, 0f, -10f);
camera1.transform.rotation = Quaternion.Euler (new Vector3 (0f, 0f, angle));
}
}
}
void OnTriggerStay2D(Collider2D col) {
Debug.Log("Trigger entered....");
isInCollider = true;
}
If you have any questions,, please ask. Thanks in advance!
Answer by lloladin · Nov 29, 2015 at 04:27 PM
to me it seems like its bc you are using
Input.GetKey (KeyCode.E))
which means you want this to happend whenever you hold down the key so it will run the code multiple times you probly want to use
Input.GetKeyDown (KeyCode.E))
this should fix that you enter the exit alot of times not sure if it will fix the camera not always changeing postion hope this helps