2020年1月1日 星期三

Unity筆記:如何將2D物件移動至滑鼠點擊的位置?




----
很基本的功能,簡單記錄一下。
----

Vector2.MoveTowards

public static Vector2 MoveTowards
(Vector2 current, Vector2 target, float maxDistanceDelta);

Description

Moves a point current towards target.

This is essentially the same as Vector2.Lerp but instead the function will ensure that the distance never exceeds maxDistanceDelta. Negative values of maxDistanceDelta pushes the vector away from target.


maxDistanceDelta可以理解為每次移動的最大距離,
為負時會向目標位置反向推離。


using UnityEngine;

// 2D MoveTowards example
// Move the sprite to where the mouse is clicked
//
// Set speed to -1.0f and the sprite will move
// away from the mouse click position forever

public class ExampleClass : MonoBehaviour
{
    private float speed = 10.0f;
    private Vector2 target;
    private Vector2 position;
    private Camera cam;

    void Start()
    {
        target = new Vector2(0.0f, 0.0f);
        position = gameObject.transform.position;

        cam = Camera.main;
    }

    void Update()
    {
        float step = speed * Time.deltaTime;

        // move sprite towards the target location
        transform.position = Vector2.MoveTowards(transform.position, target, step);
    }

    void OnGUI()
    {
        Event currentEvent = Event.current;
        Vector2 mousePos = new Vector2();
        Vector2 point = new Vector2();

        // compute where the mouse is in world space
        mousePos.x = currentEvent.mousePosition.x;
        mousePos.y = cam.pixelHeight - currentEvent.mousePosition.y;
        point = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 0.0f));

        if (Input.GetMouseButtonDown(0))
        {
            // set the target to the mouse click location
            target = point;
        }
    }
}


順帶一提,只要在給予位置後同時把相機位置跟隨正在移動的單位,
加上:
cam.transform.position = transform.position + new Vector3(0,0,-10);
就可以簡單的做出一個跟著滑鼠點擊自由移動且有相機跟隨的物件了,
換句話說,這東西就可以在Unity的世界無盡地自由奔馳了,
當然,實際畫面中需要有相對參考點才能有移動的感覺,
譬如移動到地圖外什麼也沒有的虛空中的話,
觀察者是沒辦法感受到移動的。

另外,通常會改用按鈕之類的UI來當觸發器,
好處是可以讓UI覆蓋在點擊移動的範圍上面,
避免點擊UI的同時也移動到地圖的單位。
(:3ぅ)
----

1 則留言:

你發現了這篇網誌的留言板,在這留點什麼吧|д・)