向量的加法和减法运算

using System;
using System.Collections;
using System.Collections.Generic;


/**
 * 向量的加法和减法运算
 */
public class Vector3D
{
    public float x, y, z;
    public Vector3D(float x=0f,float y =0f,float z= 0f)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }
    public Vector3D(Vector3D vec)
    {
        this.x = vec.x;
        this.y = vec.y;
        this.z = vec.z;
    }
    public Vector3D add(Vector3D vec)
    {
        Vector3D ret = new Vector3D(x, y, z);
        ret.x += vec.x;
        ret.y += vec.y;
        ret.z += vec.z;
        return ret;
    }
    public Vector3D sub(Vector3D vec)
    {
        Vector3D ret = new Vector3D(x, y, z);
        ret.x -= vec.x;
        ret.y -= vec.y;
        ret.z -= vec.z;
        return ret;
    }

    //向量规范化(单位化),让向量的长度为1
    public void normalize()
    {
        float lenth = (float)Math.Sqrt(x * x + y * y + z * z);//取模
        x /= lenth;
        y /= lenth;
        z /= lenth;
    }
    public override string ToString()
    {
        return string.Format("(" + x + "," + y + "," + z + ")");
    }

    // 操作符重载
    public static Vector3D operator + (Vector3D lv,Vector3D rv)
    {
        return lv.add(rv);
    }
    public static Vector3D operator - (Vector3D lv,Vector3D rv)
    {
        return lv.sub(rv);
    }

}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/**
 * 自己写的Vector3D与u3d的Vector3比较验证是否正确
 */
public class NewBehaviourScript : MonoBehaviour
{
    public bool isEqual(Vector3D ov,Vector3 uv)
    {
        if (ov.x == uv.x && ov.y == uv.y && ov.z == uv.z)
        {
            return true;
        }
        return false;
    }
    // Start is called before the first frame update
    void Start()
    {
        Vector3D ov1 = new Vector3D(1.1f, 1.2f, 1.3f) + new Vector3D(1, 2, 3);
        Vector3 uv1 = new Vector3(1.1f, 1.2f, 1.3f) + new Vector3(1, 2, 3);
        if (isEqual(ov1, uv1))
        {
            Debug.Log("add equal...");
        }
        Vector3D ov2 = new Vector3D(1.1f, 1.2f, 1.3f) - new Vector3D(1, 2, 3);
        Vector3 uv2 = new Vector3(1.1f, 1.2f, 1.3f) - new Vector3(1, 2, 3);
        if (isEqual(ov1, uv1))
        {
            Debug.Log("sub equal...");
        }
        ov2.normalize();
        uv2.Normalize();
        if (isEqual(ov2, uv2))
        {
            Debug.Log("nrm equal...");
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

猜你喜欢

转载自www.cnblogs.com/fly-book/p/10987955.html