유니티에서 자동차 오브젝트의 속도를 줄이는 예
앞선 내용 참고 : http://micropilot.tistory.com/category/Unity3D%20Car/Steer%20Ratio
키보드의 방향키 중에서 전(Up), 후(Down) 방향키를 누르면 자동차의 속도가 증가하고 키를 누르지 않으면 감속되어 점차 멈추는 예제이다.
using UnityEngine;
using System.Collections;
public class Car : MonoBehaviour {
// 자동차 바퀴 방향조종을 위한 Transform 4개
public Transform tireTransformFL;
public Transform tireTransformFR;
public Transform tireTransformRL;
public Transform tireTransformRR;
public WheelCollider colliderFR;
public WheelCollider colliderFL;
public WheelCollider colliderRR;
public WheelCollider colliderRL;
// 바퀴 회전을 위한 Transform
public Transform wheelTransformFL;
public Transform wheelTransformFR;
public Transform wheelTransformRL;
public Transform wheelTransformRR;
// 속도에 따라서 방향전환율을 다르게 적용하기 위한 준비
public float highestSpeed = 500f;
public float lowSpeedSteerAngle = 0.1f;
public float highSpeedStreerAngle = 25f;
// 감속량
public float decSpeed = 7f;
public int maxTorque = 10;
private float prevSteerAngle;
// Use this for initialization
void Start () {
rigidbody.centerOfMass = new Vector3(0,-1,0); // 무게중심이 높으면 차가 쉽게 전복된다
}
// Update is called once per frame
void FixedUpdate () {
Control ();
}
void Update() {
// 앞바퀴 2개를 이동방향으로 향하기
tireTransformFL.Rotate (Vector3.up, colliderFL.steerAngle-prevSteerAngle, Space.World);
tireTransformFR.Rotate (Vector3.up, colliderFR.steerAngle-prevSteerAngle, Space.World);
prevSteerAngle = colliderFR.steerAngle;
}
void Control() {
//전진, 후진
colliderRR.motorTorque = -maxTorque * Input.GetAxis("Vertical");
colliderRL.motorTorque = -maxTorque * Input.GetAxis("Vertical");
// 전후진 키를 누르지 않으면 제동이 걸리도록 한다
if (!Input.GetButton ("Vertical")) {
colliderRR.brakeTorque = decSpeed;
colliderRL.brakeTorque = decSpeed;
} else {
colliderRR.brakeTorque = 0;
colliderRL.brakeTorque = 0;
}
// 속도에 따라 방향전환율을 달리 적용하기 위한 계산
float speedFactor = rigidbody.velocity.magnitude / highestSpeed;
/** Mathf.Lerp(from, to, t) : Linear Interpolation(선형보간)
* from:시작값, to:끝값, t:중간값(0.0 ~ 1.0)
* t가 0이면 from을 리턴, t가 1이면 to 를 리턴함, 0.5라면 from, to 의 중간값이 리턴됨
*/
float steerAngle = Mathf.Lerp (lowSpeedSteerAngle, highSpeedStreerAngle, 1/speedFactor);
//print ("steerAngle:" + steerAngle);
steerAngle *= Input.GetAxis("Horizontal");
//좌우 방향전환
colliderFR.steerAngle = steerAngle;
colliderFL.steerAngle = steerAngle;
/*colliderFR.steerAngle = 17 * Input.GetAxis("Horizontal");
colliderFL.steerAngle = 17 * Input.GetAxis("Horizontal"); */
// 바퀴회전효과
wheelTransformFL.Rotate (colliderFL.rpm/60*360 * Time.fixedDeltaTime, 0, 0);
wheelTransformFR.Rotate (colliderFR.rpm/60*360 * Time.fixedDeltaTime, 0, 0);
wheelTransformRL.Rotate (colliderRL.rpm/60*360 * Time.fixedDeltaTime, 0, 0);
wheelTransformRR.Rotate (colliderRR.rpm/60*360 * Time.fixedDeltaTime, 0, 0);
}
}