Unity3D Car/Skid Smoke

Car Skid Smoke effect in Unity

Soul-Learner 2015. 4. 8. 19:03

유니티에서 자동차의 스키드 연기를 표현하는 간단한 예


앞선 내용 참고 : http://micropilot.tistory.com/category/Unity3D%20Car/Skid%20Texture


자동차의 바퀴가 지면과 마찰이 심해지면 바퀴에서 흰 연기가 나는 현상을 볼 수가 있는데, 유니티에서 쉽게 설정하는 방법을 알아보려고 한다. 여기서는 ParticleSystem 이라는 GameObject 를 Prefab으로 등록하고 스크립트에서 필요시에 인스턴스를 생성하는 방법을 사용하려고 한다




[ParticleSystem 설정 절차]

  1. GameObject > Create Other > Particle System
  2. Hierarchy 뷰에 추가된 Particle System을 선택하고 Inspector 뷰에서 다양한 속성을 설정한다
  3. Project 뷰에 Prefab을 생성하고 Hierarchy 뷰의 Particle System 을 드래그하여 할당한다
  4. Hierarchy 뷰의 Particle System 은 삭제한다
  5. 스크립트에 GameObject 변수를 선언하고 위에서 생성한 Prefab 을 드래그하여 할당한다 (Inspector 뷰 사용)



아래의 코드를 WheelCollider 콤포넌트가 포함된 오브젝트에 드래그하여 할당하면 된다


[Particle System 프리팹의 인스턴스를 생성하여 연기를 출력하는 스크립트]

using UnityEngine;

using System.Collections;


public class SkidSound : MonoBehaviour {


public float currentFrictionValue;

public GameObject skidSound;

private float waitTime = 0.1f;


public GameObject skidPrefab;


public GameObject skidSmoke; // Project 뷰의 Particle System 프리팹을 드래그하여 할당한 원본 오브젝트


void Start () {

}


void Update () {

WheelHit hit;

transform.GetComponent<WheelCollider>().GetGroundHit(out hit);

currentFrictionValue = hit.sidewaysSlip;

currentFrictionValue = Mathf.Abs (currentFrictionValue);

if (currentFrictionValue >= 1.5f && waitTime>=0.1f) {

Instantiate(skidSound, hit.point, Quaternion.identity);

GameObject smokeInstance = (GameObject)Instantiate (skidSmoke, hit.point, Quaternion.identity);

smokeInstance.AddComponent<GameObjectDestroy>();

waitTime = 0f;

}else{

waitTime += Time.deltaTime;

}


if (currentFrictionValue >= 1.5f){

setSkidMark();

}

}


private Vector3 prevPos = Vector3.zero;

private float skidTime;

void setSkidMark() {

WheelHit hit;

transform.GetComponent<WheelCollider>().GetGroundHit(out hit);

if (prevPos == Vector3.zero){

prevPos = hit.point;

return;

}

if(skidTime>0.05f){

Vector3 relativePos = prevPos - hit.point;;

Quaternion rot = Quaternion.LookRotation(relativePos);

GameObject skidInstance = (GameObject)Instantiate (skidPrefab, hit.point, rot);

prevPos = hit.point;

skidInstance.AddComponent<GameObjectDestroy> ();

skidTime = 0;

}else{

skidTime += Time.deltaTime;

}

}

}



아래의 코드를 위의 코드의 경우처럼 스크립트에서 동적으로 프리팹 인스턴스에 추가하거나 Inspector 뷰로 드래그하여 추가하면 된다


[위의 코드에서 사용되어 Particle System 인스턴스를  2초후에 삭제하는 스크립트]

using UnityEngine;

using System.Collections;


public class GameObjectDestroy : MonoBehaviour {

private float destroyTime;

void Start () {

}

void Update () {

if(destroyTime>=2f) {

Destroy(gameObject);

}else {

destroyTime += Time.deltaTime;

}

}

}