블로그 이미지
Every unexpected event is a path to learning for you. blueasa

카테고리

분류 전체보기 (2845)
Unity3D (891)
Programming (479)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (188)
협업 (64)
3DS Max (3)
Game (12)
Utility (141)
Etc (99)
Link (33)
Portfolio (19)
Subject (90)
iOS,OSX (52)
Android (16)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (19)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday

Finite State Machine

Contents

 [hide

Description

This is a Deterministic Finite State Machine framework based on chapter 3.1 of Game Programming Gems 1 by Eric Dybsend. Therea are two classes and two enums. Include them in your project, and follow the explanations to get the FSM working properly. There´s also a complete example script at the end of this page.

Components

  • Transition enum: this enum contains the lables to the transitions that can be fired by the system. Don´t change the first lable, NullTransition, as the FSMSystem class uses it.
  • StateID enum: this is the ID of the states the game may have. You could use references to the real States´ classes but using enums makes the system less susceptible to have code having access to objects it is not supposed to. All the states´ ids should be placed here. Don´t change the first lable, NullStateID, as the FSMSystem class uses it.
  • FSMState class: this class has a Dictionaty with pairs (Transition-StateID) indicating which new state S2 the FSM should go to when a transition T is fired and the current state is S1. It has methods to add and delete pairs (Transition-StateID), a method to check which state to go to if a trasition is passed to it. Two methods are used in the example given to check which transition should be fired (Reason()) and which action(s) (Act()) the GameObject that has the FSMState attached should do. You don´t have to use this schema, but some kind of transition-action code must be used in your game.
  • FSMSystem: This is the Finite State Machine class that each NPC or GameObject in your game must have in order to use the framework. It stores the NPC´s States in a List, has methods to add and delete a state and a method to change the current state based on a transition passed to it (PerformTransition()). You can call this method anywhere within your code, as in a collision test, or within Update() or FixedUpdate().

C# - FSMSystem.cs

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
/**
A Finite State Machine System based on Chapter 3.1 of Game Programming Gems 1 by Eric Dybsand
 
Written by Roberto Cezar Bianchini, Jully 2010
 
 
How to use:
	1. Place the lables for the transitions and the states of the Finite State System
	    in the corresponding enums.
 
	2. Write new class(es) inheriting from FSMState and fill each one with pairs (transition-state).
	    These pairs represent the state S2 the FSMSystem should be if while being on state S1, a
	    transition T is fired and state S1 has a transintion from it to S2. Remember this is a Deterministic FSM. 
	    You can´t have one transition leading to two different states.
 
	   Method Reason is used to determine which transition should be fired.
	   You can write the code to fire transitions in another place, and leave this method empty if you
	   feel it´s more appropriate to your project.
 
	   Method Act has the code to perform the actions the NPC is supposed do if it´s on this state.
	   You can write the code for the actions in another place, and leave this method empyt if you
	   feel it´s more appropriate to your project.
 
	3. Create an instance of FSMSystem class and add the states to it.
 
	4. Call Reason and Act (or whicheaver methods you have for firing transitions and making the NPCs
	     behave in your game) from your Update or FixedUpdate methods.
 
	Assynchronous transitions from Unity Engine, like OnTriggerEnter, SendMessage, can also be used, 
	just call the Method PerformTransition from your FSMSystem instance with the correct Transition 
	when the event occurs.
 
 
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 
AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
 
 
/// <summary>
/// Place the lables for the Transitions in this enum.
/// Don´t change the first lable, NullTransition as FSMSystem class uses it.
/// </summary>
public enum Transition
{
    NullTransition = 0, // Use this transition to represent a non-existint transition in your system
}
 
/// <summary>
/// Place the lables for the States in this enum.
/// Don´t change the first lable, NullTransition as FSMSystem class uses it.
/// </summary>
public enum StateID
{
    NullStateID = 0, // Use this ID to represent a non-existing State in your system	
}
 
/// <summary>
/// This class represents the States in the Finite State System.
/// Each state has a Dictionary with pairs (transition-state) showing
/// which state the FSM should be if a transition is fired while this state
/// is the current state.
/// Method Reason is used to determine which transition should be fired .
/// Method Act has the code to perform the actions the NPC is supposed do if it´s on this state.
/// </summary>
public abstract class FSMState
{
    protected Dictionary<Transition, StateID> map = new Dictionary<Transition, StateID>();
    protected StateID stateID;
    public StateID ID { get { return stateID; } }
 
    public void AddTransition(Transition trans, StateID id)
    {
        // Check if anyone of the args is invallid
        if (trans == Transition.NullTransition)
        {
            Debug.LogError("FSMState ERROR: NullTransition is not allowed for a real transition");
            return;
        }
 
        if (id == StateID.NullStateID)
        {
            Debug.LogError("FSMState ERROR: NullStateID is not allowed for a real ID");
            return;
        }
 
        // Since this is a Deterministc FSM,
        //   check if the current transition was already inside the map
        if (map.ContainsKey(trans))
        {
            Debug.LogError("FSMState ERROR: State " + stateID.ToString() + " already has transition " + trans.ToString() + 
                           "Impossible to assign to another state");
            return;
        }
 
        map.Add(trans, id);
    }
 
    /// <summary>
    /// This method deletes a pair transition-state from this state´s map.
    /// If the transition was not inside the state´s map, an ERROR message is printed.
    /// </summary>
    public void DeleteTransition(Transition trans)
    {
        // Check for NullTransition
        if (trans == Transition.NullTransition)
        {
            Debug.LogError("FSMState ERROR: NullTransition is not allowed");
            return;
        }
 
        // Check if the pair is inside the map before deleting
        if (map.ContainsKey(trans))
        {
            map.Remove(trans);
            return;
        }
        Debug.LogError("FSMState ERROR: Transition " + trans.ToString() + " passed to " + stateID.ToString() + 
                       " was not on the state´s transition list");
    }
 
    /// <summary>
    /// This method returns the new state the FSM should be if
    ///    this state receives a transition and 
    /// </summary>
    public StateID GetOutputState(Transition trans)
    {
        // Check if the map has this transition
        if (map.ContainsKey(trans))
        {
            return map[trans];
        }
        return StateID.NullStateID;
    }
 
    /// <summary>
    /// This method is used to set up the State condition before entering it.
    /// It is called automatically by the FSMSystem class before assigning it
    /// to the current state.
    /// </summary>
    public virtual void DoBeforeEntering() { }
 
    /// <summary>
    /// This method is used to make anything necessary, as reseting variables
    /// before the FSMSystem changes to another one. It is called automatically
    /// by the FSMSystem before changing to a new state.
    /// </summary>
    public virtual void DoBeforeLeaving() { } 
 
    /// <summary>
    /// This method decides if the state should transition to another on its list
    /// NPC is a reference to the object that is controlled by this class
    /// </summary>
    public abstract void Reason(GameObject player, GameObject npc);
 
    /// <summary>
    /// This method controls the behavior of the NPC in the game World.
    /// Every action, movement or communication the NPC does should be placed here
    /// NPC is a reference to the object that is controlled by this class
    /// </summary>
    public abstract void Act(GameObject player, GameObject npc);
 
} // class FSMState
 
 
/// <summary>
/// FSMSystem class represents the Finite State Machine class.
///  It has a List with the States the NPC has and methods to add,
///  delete a state, and to change the current state the Machine is on.
/// </summary>
public class FSMSystem
{
    private List<FSMState> states;
 
    // The only way one can change the state of the FSM is by performing a trasintion
    // Don´t change the CurrentState directly
    private StateID currentStateID;
    public StateID CurrentStateID { get { return currentStateID; } }
    private FSMState currentState;
    public FSMState CurrentState { get { return currentState; } }
 
    public FSMSystem()
    {
        states = new List<FSMState>();
    }
 
    /// <summary>
    /// This method places new states inside the FSM,
    /// or prints an ERROR message if the state was already inside the List.
    /// First state added is also the initial state.
    /// </summary>
    public void AddState(FSMState s)
    {
        // Check for Null reference before deleting
        if (s == null)
        {
            Debug.LogError("FSM ERROR: Null reference is not allowed");
        }
 
        // First State inserted is also the Initial state,
        //   the state the machine is in when the simulation begins
        if (states.Count == 0)
        {
            states.Add(s);
            currentState = s;
            currentStateID = s.ID;
            return;
        }
 
        // Add the state to the List if it´s not inside it
        foreach (FSMState state in states)
        {
            if (state.ID == s.ID)
            {
                Debug.LogError("FSM ERROR: Impossible to add state " + s.ID.ToString() + 
                               " because state has already been added");
                return;
            }
        }
        states.Add(s);
    }
 
    /// <summary>
    /// This method delete a state from the FSM List if it exists, 
    ///   or prints an ERROR message if the state was not on the List.
    /// </summary>
    public void DeleteState(StateID id)
    {
        // Check for NullState before deleting
        if (id == StateID.NullStateID)
        {
            Debug.LogError("FSM ERROR: NullStateID is not allowed for a real state");
            return;
        }
 
        // Search the List and delete the state if it´s inside it
        foreach (FSMState state in states)
        {
            if (state.ID == id)
            {
                states.Remove(state);
                return;
            }
        }
        Debug.LogError("FSM ERROR: Impossible to delete state " + id.ToString() + 
                       ". It was not on the list of states");
    }
 
    /// <summary>
    /// This method tries to change the state the FSM is in based on
    /// the current state and the transition passed. If current state
    ///  doesn´t have a target state for the transition passed, 
    /// an ERROR message is printed.
    /// </summary>
    public void PerformTransition(Transition trans)
    {
        // Check for NullTransition before changing the current state
        if (trans == Transition.NullTransition)
        {
            Debug.LogError("FSM ERROR: NullTransition is not allowed for a real transition");
            return;
        }
 
        // Check if the currentState has the transition passed as argument
        StateID id = currentState.GetOutputState(trans);
        if (id == StateID.NullStateID)
        {
            Debug.LogError("FSM ERROR: State " + currentStateID.ToString() +  " does not have a target state " + 
                           " for transition " + trans.ToString());
            return;
        }
 
        // Update the currentStateID and currentState		
        currentStateID = id;
        foreach (FSMState state in states)
        {
            if (state.ID == currentStateID)
            {
                // Do the post processing of the state before setting the new one
                currentState.DoBeforeLeaving();
 
                currentState = state;
 
                // Reset the state ot its desired contition before it can reason or act
                currentState.DoBeforeEntering();
                break;
            }
        }
 
    } // PerformTransition()
 
} //class FSMSystem

Example

Here´s an example that implements the above framework. The gameobject with this script follows a path of waypoints and starts chasing a target if it comes within a certain distance from it. Attach this class to your NPC. Besides the framework transition and stateid enums, you also have to setup a reference to the waypoints and to the target (player). I used FixedUpdate() in the MonoBehaviour because the NPC reasoning schema doesn´t need to be called everyframe, but you can change that and use Update().

using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
 
[RequireComponent(typeof(Rigidbody))]
public class NPCControl : MonoBehaviour
{
    public GameObject player;
    public Transform[] path;
    private FSMSystem fsm;
 
    public void SetTransition(Transition t) { fsm.PerformTransition(t); }
 
    public void Start()
    {
        MakeFSM();
    }
 
    public void FixedUpdate()
    {
        fsm.CurrentState.Reason(player, gameObject);
        fsm.CurrentState.Act(player, gameObject);
    }
 
	// The NPC has two states: FollowPath and ChasePlayer
	// If it´s on the first state and SawPlayer transition is fired, it changes to ChasePlayer
	// If it´s on ChasePlayerState and LostPlayer transition is fired, it returns to FollowPath
    private void MakeFSM()
    {
        FollowPathState follow = new FollowPathState(path);
        follow.AddTransition(Transition.SawPlayer, StateID.ChasingPlayer);
 
        ChasePlayerState chase = new ChasePlayerState();
        chase.AddTransition(Transition.LostPlayer, StateID.FollowingPath);
 
        fsm = new FSMSystem();
        fsm.AddState(follow);
        fsm.AddState(chase);
    }
}
 
public class FollowPathState : FSMState
{
    private int currentWayPoint;
    private Transform[] waypoints;
 
    public FollowPathState(Transform[] wp) 
    { 
        waypoints = wp;
        currentWayPoint = 0;
        stateID = StateID.FollowingPath;
    }
 
    public override void Reason(GameObject player, GameObject npc)
    {
        // If the Player passes less than 15 meters away in front of the NPC
        RaycastHit hit;
        if (Physics.Raycast(npc.transform.position, npc.transform.forward, out hit, 15F))
        {
            if (hit.transform.gameObject.tag == "Player")
                npc.GetComponent<NPCControl>().SetTransition(Transition.SawPlayer);
        }
    }
 
    public override void Act(GameObject player, GameObject npc)
    {
        // Follow the path of waypoints
		// Find the direction of the current way point 
        Vector3 vel = npc.rigidbody.velocity;
        Vector3 moveDir = waypoints[currentWayPoint].position - npc.transform.position;
 
        if (moveDir.magnitude < 1)
        {
            currentWayPoint++;
            if (currentWayPoint >= waypoints.Length)
            {
                currentWayPoint = 0;
            }
        }
        else
        {
            vel = moveDir.normalized * 10;
 
            // Rotate towards the waypoint
            npc.transform.rotation = Quaternion.Slerp(npc.transform.rotation,
                                                      Quaternion.LookRotation(moveDir),
                                                      5 * Time.deltaTime);
            npc.transform.eulerAngles = new Vector3(0, npc.transform.eulerAngles.y, 0);
 
        }
 
        // Apply the Velocity
        npc.rigidbody.velocity = vel;
    }
 
} // FollowPathState
 
public class ChasePlayerState : FSMState
{
    public ChasePlayerState()
    {
        stateID = StateID.ChasingPlayer;
    }
 
    public override void Reason(GameObject player, GameObject npc)
    {
        // If the player has gone 30 meters away from the NPC, fire LostPlayer transition
        if (Vector3.Distance(npc.transform.position, player.transform.position) >= 30)
            npc.GetComponent<NPCControl>().SetTransition(Transition.LostPlayer);
    }
 
    public override void Act(GameObject player, GameObject npc)
    {
        // Follow the path of waypoints
		// Find the direction of the player 		
        Vector3 vel = npc.rigidbody.velocity;
        Vector3 moveDir = player.transform.position - npc.transform.position;
 
        // Rotate towards the waypoint
        npc.transform.rotation = Quaternion.Slerp(npc.transform.rotation,
                                                  Quaternion.LookRotation(moveDir),
                                                  5 * Time.deltaTime);
        npc.transform.eulerAngles = new Vector3(0, npc.transform.eulerAngles.y, 0);
 
        vel = moveDir.normalized * 10;
 
        // Apply the new Velocity
        npc.rigidbody.velocity = vel;
    }
 
} // ChasePlayerState


출처 : http://wiki.unity3d.com/index.php/Finit_State_Machine

반응형

'Unity3D > Design Pattern' 카테고리의 다른 글

유니티 4.2버전에 대한 Simple Observer Pattern  (0) 2013.12.02
Posted by blueasa
, |

스크롤/드래그 이벤트를 받는 방법

  • NGUI에서는 BoxCollider를 붙인 오브젝트만  UICamera의 마우스 이벤트를 받는다
    • BoxCollider 뿐만 아니라  Collider면 다 될 것 같긴 하지만 확인해보진 않았다
  • 따라서 BoxCollider와 UIDragPanelContents를 붙인 오브젝트에 UIForwardEvents 스크립트를 붙인다
  • UIForwardEvents의 OnDrag를 true로 설정하고, UIForwardEvents의 target을 UIDragPanelContents 오브젝트로 지정한다
  • UIDragPanelContents 오브젝트에 UIEventListener 스크립트를 붙이고 이벤트를 받거나, 직접 OnDrag() 를 구현한다
  • OnScroll은 위 과정을 참고하여 알아서 구현한다




반응형

'Unity3D > NGUI' 카테고리의 다른 글

NGUI: Events(Event Functions)  (2) 2012.12.07
NGUI Virtual Joystick  (1) 2012.12.05
유니티 NGUI 에서 라벨에 한글(폰트) 적용하기  (2) 2012.11.05
NGUI - Sticky Floating Text  (0) 2012.10.28
NGUI: HUD Text  (0) 2012.10.26
Posted by blueasa
, |


링크 : http://clack.tistory.com/89

반응형
Posted by blueasa
, |


링크 : http://blog.naver.com/khaetnim/100158344211

반응형

'Unity3D > Effect' 카테고리의 다른 글

Scrolling UVs  (0) 2012.11.08
MeleeWeaponTrail  (0) 2012.10.11
Posted by blueasa
, |

Scrolling UVs

Unity3D/Effect / 2012. 11. 8. 16:03

Scrolling UVs

Overview

A C# script that smoothly scrolls a material's UVs in an arbitrary direction/speed given by "Uv Animation Rate". Supports changing which material index and texture name, but the defaults will work with single material, single texture renderers.

C#

using UnityEngine;
using System.Collections;
 
public class ScrollingUVs : MonoBehaviour 
{
    public int materialIndex = 0;
    public Vector2 uvAnimationRate = new Vector2( 1.0f, 0.0f );
    public string textureName = "_MainTex";
 
    Vector2 uvOffset = Vector2.zero;
 
    void LateUpdate() 
    {
        uvOffset += ( uvAnimationRate * Time.deltaTime );
        if( renderer.enabled )
        {
            renderer.materials[ materialIndex ].SetTextureOffset( textureName, uvOffset );
        }
    }
}



출처 : http://wiki.unity3d.com/index.php/Scrolling_UVs

반응형

'Unity3D > Effect' 카테고리의 다른 글

파티클 한 번만 사용하고 종료하기  (0) 2012.11.08
MeleeWeaponTrail  (0) 2012.10.11
Posted by blueasa
, |

toon-water shader

Unity3D/Shader / 2012. 11. 7. 00:13


링크 : http://forum.unity3d.com/threads/41401-Problem-with-own-toon-water-shader-(lighting)

반응형

'Unity3D > Shader' 카테고리의 다른 글

Toon/Tf2Shader  (0) 2013.07.19
Toon/Basic with Alpha  (0) 2013.07.19
Toon/Lighted with Alpha  (0) 2013.07.19
스크립트로 Shader 변경  (0) 2012.11.06
AlphaVertexColor  (0) 2012.11.04
Posted by blueasa
, |

Smooth Follow Camera

Unity3D / 2012. 11. 6. 00:10

SmoothFollow2

Author: Daniel

Improved Version

Author: Vasilis Christopoulos & Daniel Toliaferro

Contents

 [hide

Description

This is designed to make a camera smoothly follow a ship in space.

Usage

Place this script onto a camera.

JavaScript - SmoothFollow2.js

var target : Transform;
var distance = 3.0;
var height = 3.0;
var damping = 5.0;
var smoothRotation = true;
var rotationDamping = 10.0;

function Update () {
	var wantedPosition = target.TransformPoint(0, height, -distance);
	transform.position = Vector3.Lerp (transform.position, wantedPosition, Time.deltaTime * damping);

	if (smoothRotation) {
		var wantedRotation = Quaternion.LookRotation(target.position - transform.position, target.up);
		transform.rotation = Quaternion.Slerp (transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
	}

	else transform.LookAt (target, target.up);
}

C# - SmoothFollow2.cs

using UnityEngine;
using System.Collections;

public class SmoothFollow2 : MonoBehaviour {
	public Transform target;
	public float distance = 3.0f;
	public float height = 3.0f;
	public float damping = 5.0f;
	public bool smoothRotation = true;
	public float rotationDamping = 10.0f;
	
	void Update () {
		Vector3 wantedPosition = target.TransformPoint(0, height, -distance);
		transform.position = Vector3.Lerp (transform.position, wantedPosition, Time.deltaTime * damping);

		if (smoothRotation) {
			Quaternion wantedRotation = Quaternion.LookRotation(target.position - transform.position, target.up);
			transform.rotation = Quaternion.Slerp (transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
		}
		
		else transform.LookAt (target, target.up);
	}
}

C# - SmoothFollow2.cs (Improved)

using UnityEngine;
using System.Collections;

        public class SmoothFollow2 : MonoBehaviour {
        public Transform target;
        public float distance = 3.0f;
        public float height = 3.0f;
        public float damping = 5.0f;
        public bool smoothRotation = true;
        public bool followBehind = true;
        public float rotationDamping = 10.0f;

        void Update () {
               Vector3 wantedPosition;
               if(followBehind)
                       wantedPosition = target.TransformPoint(0, height, -distance);
               else
                       wantedPosition = target.TransformPoint(0, height, distance);
     
               transform.position = Vector3.Lerp (transform.position, wantedPosition, Time.deltaTime * damping);

               if (smoothRotation) {
                       Quaternion wantedRotation = Quaternion.LookRotation(target.position - transform.position, target.up);
                       transform.rotation = Quaternion.Slerp (transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
               }
               else transform.LookAt (target, target.up);
         }
}


출처 : http://wiki.unity3d.com/index.php/SmoothFollow2

반응형
Posted by blueasa
, |

... 

string shaderName = "Mobile/Unlit (Supports Lightmap)";

GameObject sampleObject;

...

 

MeshRenderer mr = sampleObject.GetComponent<MeshRenderer>();   // 일단 MeshRenderer 컴포넌트를 얻고

mr.material.shader = Shader.Find(shaderName);                                 // 쉐이더를 찾아(이름으로) 변경

 

 

 

 

<출처> http://unity3d.com/support/documentation/ScriptReference/Material-shader.html



출처 : http://blog.naver.com/kzh8055/140158747595

반응형

'Unity3D > Shader' 카테고리의 다른 글

Toon/Tf2Shader  (0) 2013.07.19
Toon/Basic with Alpha  (0) 2013.07.19
Toon/Lighted with Alpha  (0) 2013.07.19
toon-water shader  (0) 2012.11.07
AlphaVertexColor  (0) 2012.11.04
Posted by blueasa
, |

Mathf.SmoothDamp

Unity3D/Math / 2012. 11. 6. 00:00

Mathf.SmoothDamp



함수 원형


static function SmoothDamp ( current : float, 

                                          target : float, 

                                          ref currentVelocity : float, 

                                          smoothTime : float, 

                                          maxSpeed : float = Mathf.Infinity, 

                                          deltaTime : float = Time.deltaTime) : float Parameters

    


매개변수


current             : 현재 위치 

target               : 타겟 위치

currentVelocity  : 호출할때마다 이 함수에 의해 변경( 계산 )되는 현재속도

smoothTime      : 현재 위치에서 목적 위치까지 이르는데 걸리는 시간. 이 값이 작을수록 목적지에 빠르게 도착한다.

maxSpeed        : 스피드의 상한치.

deltaTime         : By default Time.deltaTime.



설명


Gradually changes a value towards a desired goal over time.


The value is smoothed by some spring-damper like function, which will never overshoot.

The function can be used to smooth any kind of value, positions, colors, scalars.


시간 내에 정해진 목표(값)로 점점 값을 변화시킨다.


결코 특정값을 넘지 않게 하는 스프링 제동 기능으로써 값을 자연스럽게 변화하게 한다.

이 함수는 어떤 종류의 값, 위치, 색, 스칼라등의 어떤 종류의 값이라도 자연스럽게 변화시키는데 이용될수 있다.





사용예


using UnityEngine;

using System.Collections;


public class example : MonoBehaviour {


    public Transform target;

    public float smoothTime = 0.3F;

    private float yVelocity = 0.0F;


    void Update() {

        float newPosition = Mathf.SmoothDamp(transform.position.y, target.position.y, ref yVelocity, smoothTime);

        transform.position = new Vector3(transform.position.x, newPosition, transform.position.z);

    }

}





이 함수를 이용하는 목적은 자연스러운( 부드러운 ) 감속, 가속 효과를 얻기 위함이다.

'럽츠 대탈출' 튜토리얼 에선 주인공 캐릭터를 부드럽게 따라오는 카메라의 움직임

- GPG1권에 나온 용수철 카메라 움직임

을 위해 이 함수가 사용되었다.


보통 이 함수는 다음의 형식으로 사용된다.


void Update()

{  

    ...

    current = Mathf.SmoothDamp( current, target, velocity, smoothTime );

    ...

}


시간(smoothTime)이 일정 하다면 시간이 흐를수록 

current 와 target 간의 차이가 줄어들어 결국 속도가 점점 줄어들게 될것이며,

이것을 통해 자연스로운 카메라 움직임을 표현할수 있다.


'럽츠 대탈출' 메인 게임 씬 첫 부분을 보면

카메라가 꽤 멀리떨어진 상태에서 시작해 캐릭터에게 일정한 속도로 다가가는 것을 확인할수 있는데

위의 공식대로(Mathf.SmoothDamp)라면 최초 시작 상태에서 target 과 current 의 차이가 상대적으로 크므로 

속도가 엄청 빨라야할것 같지만

- 시간은 항상 일정하고 거리차( 캐릭터와 카메라 )는 최초 시작이 가장 크므로

일정 기간 동안 속도의 변화(방향은 제외)는 없는 편이다.


이것은 smoothTime 의 다음 매개변수인 maxSpeed 의 역할 덕분인데

현재계산된 속도가 maxSpeed 값을 넘지 못하게 처리된다.


<출처: Unity Script Reference >



출처 : http://blog.naver.com/kzh8055/140154419294

반응형
Posted by blueasa
, |

유니티 NGUI 에서 라벨에 한글 적용하기(1)


유니티 NGUI 에서 라벨에 한글 적용하기(2)


반응형

'Unity3D > NGUI' 카테고리의 다른 글

NGUI Virtual Joystick  (1) 2012.12.05
스크롤/드래그 이벤트를 받는 방법  (0) 2012.11.13
NGUI - Sticky Floating Text  (0) 2012.10.28
NGUI: HUD Text  (0) 2012.10.26
NGUI와 NGUI: HUD Text 패키지 임포트 시 에러 문제..  (0) 2012.10.25
Posted by blueasa
, |