天天看點

【2.C#基礎】10.Vector類

10. Vector類

10.1 Vector類概述

在開發遊戲時,物體是被放置在空間中的,其位置一般用坐标來表示。如下圖:

【2.C#基礎】10.Vector類

為了集中管理坐标,在 3D 遊戲中可以使用 Vector3 類來管理,在 2D 遊戲中可以使用 Vector2 類來管理,Vector3 類中,Unity 提供了 x、y、z 成員變量,Vector2 類中,Unity 提供了 x、y 成員變量。對于 Vector 類,我們一般了解為向量。

10.2 Vector類的使用

1.加法運算

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

public class Vct : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Vector2 v = new Vector2(3.0f, 5.0f);
        v.x += 7.0f;
        v.y += 7.0f;
        Debug.Log(v);
    }

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

運作後控制台輸出:

(10.0, 12.0)
UnityEngine.Debug:Log(Object)
Vct:Start() (at Assets/Vct.cs:13)           

減法運算也是相同的。

2.對象之間的加法運算

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

public class Vct : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Vector2 v1 = new Vector2(3.0f, 5.0f);
        Vector2 v2 = new Vector2(7.0f, 8.0f);
        Vector2 v3 = v1 + v2;
        Debug.Log(v3);
    }

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

運作後控制台輸出:

(10.0, 13.0)
UnityEngine.Debug:Log(Object)
Vct:Start() (at Assets/Vct.cs:13)           

3.對象之間的減法運算

public class Vct : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Vector2 v1 = new Vector2(3.0f, 5.0f);
        Vector2 v2 = new Vector2(7.0f, 8.0f);
        Vector2 dir = v1 - v2; // 新的向量
        Debug.Log(dir);

        float length = dir.magnitude; // 新向量代表的長度
        Debug.Log(length);
    }

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

運作後控制台輸出:

(-4.0, -3.0)
UnityEngine.Debug:Log(Object)
Vct:Start() (at Assets/Vct.cs:13)
5
UnityEngine.Debug:Log(Object)
Vct:Start() (at Assets/Vct.cs:16)           

10.3 Vector類的應用

Vector 類可以表示坐标、向量。還可以表示加速度、力及移動速度等實體方面的數值。例如:

Vector2 speed = new Vector2(2.0f, 0.0f);
PlayPos += speed;           

其中 PlayPos 代表一個物體的坐标,在每一幀中執行上面的代碼,物體就可以按照指定的速度來移動。

繼續閱讀