using UnityEngine;
using System.Collections;
public class rotate : MonoBehaviour
{
// Use this for initialization
public GameObject gotoSign;
public static GameObject sign_t = null;
private const string mapName = "Map";
private const string mainCharacterName = "character";
private Quaternion mainCharacterRotationInit;
private GameObject mainCharacter;
void Start ()
{
mainCharacter = GameObject.Find (mainCharacterName);
mainCharacterRotationInit = mainCharacter.transform.rotation;
}
void Update ()
{
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
//发出射线
if (Physics.Raycast (ray, out hit, 500)) {
//Debug.DrawLine (ray.origin, hit.point);
//check if kick the map
if (hit.transform.name == mapName) {
//Debug.Log ("kick:" + Time.time);
//清理标记
if (sign_t) {
Destroy (sign_t, 0);
sign_t = null;
}
//change screen point to worldPoint
// can't use chinese
Vector3 p = hit.point; // Camera.main.ScreenToWorldPoint(Input.mousePosition);
// Instantiate new object
sign_t = (GameObject)Instantiate (gotoSign, new Vector3 (p.x, p.y, mainCharacter.transform.position.z), gotoSign.transform.rotation);
//we use always world up direction to compare with new vector
Vector3 thePosition = Vector3.up;
//Debug.Log ("thePosition" + thePosition);
//计算点击的点和主角位置这2点产生的向量,用来跟主角的方向求角度
Vector3 targetDir = sign_t.transform.position - mainCharacter.transform.position;
//Debug.Log ("targetDir" + targetDir);
//Debug.DrawLine (sign_t.transform.position, mainCharacter.transform.position);
// this is vector 叉乘
Vector3 tempDir = Vector3.Cross (thePosition, targetDir.normalized);
// this is vector 点乘
float dotValue = Vector3.Dot (thePosition, targetDir.normalized);
// 用点乘来计算夹角度
float angle = Mathf.Acos (dotValue) * Mathf.Rad2Deg;
if (tempDir.z>0)
{
//angle must be 0~360
angle = angle * (-1);
angle += 360;
}
//Debug.Log ("tempDir" + tempDir);
Debug.Log ( "angle" + angle);
// first init to Up
mainCharacter.transform.rotation = mainCharacterRotationInit;
// then rotate with angle
mainCharacter.transform.Rotate( new Vector3(0,angle,0));
}
}
}
}
}