美文网首页unity3D技术分享
Unity3D数学基础(Vector3)

Unity3D数学基础(Vector3)

作者: 好怕怕 | 来源:发表于2019-02-28 13:31 被阅读7次

【向量(Vector3),解释】
https://blog.csdn.net/bobo553443/article/details/79481881
我们这里主要研究transform.forward,transform.up,transform.right发生了什么?
unity公布了源码,GitHub下载源码地址:https://codeload.github.com/Unity-Technologies/UnityCsReference/zip/master

image.png
接下来我们看下Transform源码中的定义和解释:
        // The red axis of the transform in world space.
        // 世界空间变换的红色轴
        public Vector3 right
        {
            get
            {
                return rotation * Vector3.right;
            }
            set
            {
                rotation = Quaternion.FromToRotation(Vector3.right, value);
            }
        }

        // The green axis of the transform in world space.
        // 世界空间变换的绿色轴
        public Vector3 up
        {
            get
            {
                return rotation * Vector3.up;
            }
            set
            {
                rotation = Quaternion.FromToRotation(Vector3.up, value);
            }
        }

        // The blue axis of the transform in world space.
        // 世界空间变换的蓝色轴
        public Vector3 forward
        {
            get
            {
                return rotation * Vector3.forward;
            }
            set
            {
                rotation = Quaternion.LookRotation(value);
            }
        }

我们看了源码,知道了,forward内部究竟发生了什么,
比如我们想要实现一个功能,当前玩家攻击目标玩家,发射一条线,一直跟随目标,怎么实现呢?先看效果:


GIF.gif

很简单的实现就是计算两点距离,等到距离设置line的目标长度z,实时看向目标使用LookAt函数,那么问题来了,LookAt函数和forward的区别在哪里?我们也可以设置forward来实现实时朝向一个目标吗?
看代码对比差别,forward上面有,下面是lookat的源码:


        // Rotates the transform so the forward vector points at /target/'s current position.
        public void LookAt(Transform target, [UnityEngine.Internal.DefaultValue("Vector3.up")] Vector3 worldUp)
        {
            if (target)
                LookAt(target.position, worldUp);
        }

        public void LookAt(Transform target)
        {
            if (target)
                LookAt(target.position, Vector3.up);
        }

        // Rotates the transform so the forward vector points at /worldPosition/.
        public void LookAt(Vector3 worldPosition, [UnityEngine.Internal.DefaultValue("Vector3.up")] Vector3 worldUp)
        {
            Internal_LookAt(worldPosition, worldUp);
        }

        public void LookAt(Vector3 worldPosition)
        {
            Internal_LookAt(worldPosition, Vector3.up);
        }

        [FreeFunction("Internal_LookAt", HasExplicitThis = true)]
        private extern void Internal_LookAt(Vector3 worldPosition, Vector3 worldUp);

相关文章

网友评论

    本文标题:Unity3D数学基础(Vector3)

    本文链接:https://www.haomeiwen.com/subject/xwlxdqtx.html