2014년 5월 13일 화요일

Unity_2D Movement(Click to move) with NGUI

Explanation.

NGUI로 게임제작시
UI Root        
└Camera
└Pannel
            └2d Object(Sprite)
의 구조로 게임제작을 진행할때 사용하는 Movement
제목처럼 화면클릭시 목표좌표를 계산(NGUI에 맞게)한뒤
움직이는 방법.(Click to Move)
Movement2D.cs
using UnityEngine;
using System.Collections;

//click to move with NGUI
public class Movement2D : MonoBehaviour {
    private int mUIWidth = 720; // UI Root width size
    private int mUIHeight = 1280; // UI Root height size
    private int mScreenWidth = Screen.width;
    private int mScreenHeight = Screen.height;
    private int mSpeed = 200; // pixel per sec

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            clickToMove(Input.mousePosition);
        }
    }

    void clickToMove(Vector2 mousePos)
    {
        StopCoroutine("move");
        StartCoroutine("move", calcurateTargetPos(mousePos));
    }
    
    IEnumerator move(Vector2 endPos)
    {
        Vector2 startPos = transform.localPosition;
        float startTime = Time.time;
        float movedTime = Vector2.Distance(startPos, endPos) / mSpeed;
        while (Time.time - startTime < movedTime)
        {
            transform.localPosition = Vector2.Lerp(startPos, endPos, (Time.time - startTime) / movedTime);
            yield return null; // wait frame
        }
        transform.localPosition = endPos; // end Position set
    }

    Vector2 calcurateTargetPos(Vector2 mousePos)
    {
        Vector2 result;

        result.x = Mathf.Lerp(-mUIWidth / 2, mUIWidth / 2, mousePos.x / mScreenWidth);
        result.y = Mathf.Lerp(-mUIHeight / 2, mUIHeight / 2, mousePos.y / mScreenHeight);

        return result;
    }
}
Categories: ,

0 개의 댓글:

댓글 쓰기