HillClimb/Assets/Scripts/carController.cs
2023-01-22 15:59:13 +05:30

139 lines
3.6 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class carController : MonoBehaviour
{
public WheelJoint2D frontWheel;
public WheelJoint2D rearWheel;
JointMotor2D motorFront;
JointMotor2D motorBack;
public float[] SpeedF,SpeedB;
public float[] Torque;
public float[] RotationSpeed;
public float speedF;
public float speedB;
public float torqueF;
public float torqueB;
public bool TractionFront = true;
public bool TractionBack = true;
public float carRotationSpeed;
public static bool isAlive = true;
public static void GameOver(){
if(!isAlive){return;}
isAlive=false;
instance.gameOverPanel.SetActive(true);
if(PlayerPrefs.HasKey("best")){
if(PlayerPrefs.GetInt("best") < GameManager.distanceTravelled){
PlayerPrefs.SetInt("best", GameManager.distanceTravelled);
}
}else{
PlayerPrefs.SetInt("best", GameManager.distanceTravelled);
}
instance.setBest(GameManager.distanceTravelled);
}
public void setBest(int best){
if(SentBestReq){return;}
SentBestReq=true;
int earnings = (int)(GameManager.distanceTravelled/10f);
DataManager.Money+=earnings;
StartCoroutine(SetBest(best));
}
bool SentBestReq=false;
IEnumerator SetBest(int best){
WWWForm form = new WWWForm();
form.AddField("username", DataManager.Username);
form.AddField("best", best);
WWW req = new WWW(DataManager.API_Endpoint + "set_best.php", form);
yield return req;
Debug.Log(req.text);
}
public GameObject gameOverPanel;
public static carController instance{get; private set;}
void Awake()
{
instance = this;
isAlive=true;
CameraFollower.Target = transform;
speedF = SpeedF[DataManager.SpeedLevel];
speedB = SpeedB[DataManager.SpeedLevel];
torqueF = torqueB = Torque[DataManager.SpeedLevel];
carRotationSpeed = RotationSpeed[DataManager.inAirLevel];
}
// Update is called once per frame
void FixedUpdate()
{
if(!isAlive){
rearWheel.useMotor = false;
frontWheel.useMotor = false;
return;
}
if (Input.GetAxisRaw("Horizontal") > 0)
{
if (TractionFront)
{
motorFront.motorSpeed = speedF * -1;
motorFront.maxMotorTorque = torqueF;
frontWheel.motor = motorFront;
}
if (TractionBack)
{
motorBack.motorSpeed = speedF * -1;
motorBack.maxMotorTorque = torqueF;
rearWheel.motor = motorBack;
}
}
else if (Input.GetAxisRaw("Horizontal") < 0)
{
if (TractionFront)
{
motorFront.motorSpeed = speedB * -1;
motorFront.maxMotorTorque = torqueB;
frontWheel.motor = motorFront;
}
if (TractionBack)
{
motorBack.motorSpeed = speedB * -1;
motorBack.maxMotorTorque = torqueB;
rearWheel.motor = motorBack;
}
}
else
{
rearWheel.useMotor = false;
frontWheel.useMotor = false;
}
if (Input.GetAxisRaw("Horizontal") != 0)
{
GetComponent<Rigidbody2D>().AddTorque(carRotationSpeed * Input.GetAxisRaw("Horizontal") * 1);
}
// CameraFollower.UpdateFrame();
}
}