初始场景 cube的位置为(0.0.0)
摄像机位置与他的父物体
在摄像机上挂载代码如下
using UnityEngine;
using System.Collections;
public class Diretion : MonoBehaviour {
public GameObject cube;
// Use this for initialization
void Awake()
{
cube = GameObject.Find("Cube");
}
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.A))
{
//将相对 “当前游戏对象” 的坐标转化为基于世界坐标系的坐标
//Vector3 relativePosition = transform.InverseTransformPoint(Vector3 worldPosition)
//将世界坐标转化为相对 “当前游戏对象” 的基于世界坐标系的坐标
//Vector3 worldDirection = Transform.TransformDirection(Vector3 relativeDirection)
//将相对 “当前游戏对象” 的方向转化为基于世界坐标系的方向(不受父对象缩放的影响)
Vector3 worldPosition = transform.TransformPoint(0,0,2);
cube.transform.position = transform.TransformPoint(0, 0, 2);
}
}
}
运行后
此时很直观的理解到 “将相对 “当前游戏对象” 的坐标转化为基于世界坐标系的坐标”将相对于摄像机(0,0,2)的位置转换赋值给cube,使的按下A键后cube自动移动到摄像机前方2个单位处。
TransformDirection 则是转换向量。
如
vector3 Direction=transfrom.TransfromDirection(0,0,10);
cube.rigbody.addForce(Direction,forcemode.impulse);
此时物体将摄像机正前方飞出。