Unity3d中3D数学Vector3

来源:互联网 发布:经传软件 央视315 编辑:程序博客网 时间:2024/05/22 17:05

Vector3 三维向量

Struct

Representation of 3D vectors and points.

表示3D的向量和点。

This structure is used throughout Unity to pass 3D positions and directions around. It also contains functions for doing common vector operations.

这个结构用于在Unity传递3D位置和方向。它也包含做些普通向量运算的函数。

第一点:

Variables变量

  • x
    X component of the vector.
    向量的X组件。
  • y
    Y component of the vector.
    向量的Y组件。
  • z
    Z component of the vector.
    向量的Z组件。
  • this [int index]
    Access the x, y, z components using [0], [1], [2] respectively.
    使用[0], [1], [2]分别访问组件x, y, z组件。简单来说就是用索引号代替x, y, z组件。
  • normalized
    Returns this vector with a magnitude of 1 (Read Only).
    返回向量的长度为1(只读)。
  • magnitude
    Returns the length of this vector (Read Only).
    返回向量的长度(只读)。
  • sqrMagnitude
    Returns the squared length of this vector (Read Only).
    返回这个向量的长度的平方(只读)。 
注意:normalized的计算是单位长度,计算方法,把总长度magnitude/x,y,z三个位置上的和,就能够得到normalized.

Vector3.RotateTowards 转向

static function RotateTowards (current : Vector3, target : Vector3, maxRadiansDelta : float,maxMagnitudeDelta : float) : Vector3

Description描述

Rotates a vector current towards target.

当前的向量转向目标。

The vector will be rotated on an arc instead of being interpolated linearly. This is essentially the same asVector3.Slerp but instead the function will ensure that the angular speed and change of magnitude never exceeds maxRadiansDelta and maxMagnitudeDelta. Negative values of maxRadiansDelta and maxMagnitudeDelta pushes the vector away from target.

该向量将旋转在弧线上,而不是线性插值。这个函数基本上和Vector3.Lerp相同,而是该函数将确保角速度和变换幅度不会超过maxRadiansDelta和maxMagnitudeDelta。maxRadiansDelta和maxMagnitudeDelta的负值从目标推开该向量。

使用方法:

public class Roata : MonoBehaviour {
    public Transform target;
    public float speed = 1f;
    public float mag = 0.01f;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
        Debug.DrawLine(Vector3.zero,transform.position,Color.blue);
        transform.position = Vector3.RotateTowards(transform.position,target.position,speed*Time.deltaTime,mag);
}
}

speed代表是两个物体相互接近的速度。

mag代表的是跟随物体的速度。

这个方法的作用是:旋转移动到目标物体。


Vector3.ClampMagnitude 限制长度

static function ClampMagnitude (vector : Vector3, maxLength : float) : Vector3

返回向量的长度,最大不超过maxLength所指示的长度。

也就是说,钳制向量长度到一个特定的长度。

与float为半径的圆里面。

Vector3 abc;
void Start () {
        //abc = new Vector3(0,10,0);
        //abc = Vector3.ClampMagnitude(abc,2);
        abc = new Vector3(0,10,0);
        abc = Vector3.ClampMagnitude(abc,12);
        Debug.Log(abc);返回值为(0,2,0)与(0,10,0)


要是想把一个物体固定在一个范围内进行活动。

Vector3 v;
    public float radius = 1;

void Update () {
        v = transform.position;//首先把坐标信息给一个过渡坐标
        v = Vector3.ClampMagnitude(v, radius);//返回限制性的坐标
        Debug.Log(v);
        transform.position = v;重新复制给物体的位置。

这样来回循环就能锁死一个物体的位置。

0 0