u3d中的向量 vector3 vector2

Vector3(x,y,z)x代表左右,y代表上下,z代表前后

Vector3.magnitude 长度

计算两点之间的距离  。如果只给了一点的话。算出的长度其实就是和Vector3.zero点之间的长度

公式:a2+b2=c2(勾股定理)
        
2D:

3D:

计算机实现:


float Distance2D(Point2D p1,Point2D p2)
{
    float dx=p1.x-p2.x;
    float dy=p1.y-p2.y;
    float distance=sqrt(pow(dx,2)+pow(dy,2));
    return distance;
}

float Distance3D(Point3D p1,Point3D p2)
{
    float dx=p1.x-p2.x;
    float dy=p1.y-p2.y;
    float dz=p1.z-p2.z;
    float distance=sqrt(pow(dx,2)+pow(dy,2)+pow(dz,2));
    return distance;
}

Vector3.normalized

向量的规范化,实际上是两点之间的直线距离(或者某点和零点的直线距离)与两点的差值比

// Gets a vector that points from the player's position to the target's.
var heading = target.position - player.position;  //此向量指向目标对象方向,其量值等于两点之间的距离。这通常需要使用单位向量来指示其与目标的方向和距离(如抛射子弹)。
var distance = heading.magnitude;   //对象之间的距离等于指向向量的量值,将该向量除以自身量值即为单位向量:
var direction = heading / distance;  // This is now the normalized direction.

可以看到其就是各边的正弦(如果差是0的话则是0)

作用:

如果由a点向b点做直线运动。有已知速度a m/s

则a.transform.position += a.transform.position.normalized * speed*Time.deatalTime

Vector3.sqrMagnitude 长度平方

因为不用开平方,所以速度要快点,常用这个比较距离a点是否达到触碰范围。

var sqrLen = (other.position - transform.position).sqrMagnitude;

if( sqrLen < closeDistance*closeDistance )

   print ("The other transform is close to me!");

原文地址:https://www.cnblogs.com/zhepama/p/4328336.html