iLMS知識社群歷程檔登入
位置: 黃國哲 > Unity
1100318 常壓全方位移動旋轉腳本按鈕製作(簡單版)
by 黃國哲 2021-03-18 18:44:28, 回應(0), 人氣(573)
這裡使用 Event Trigger

1.首先用UI製作一個要被點選的區域(可以用圖片、Button等等)

2.Add Component 裡面選擇 Event Trigger以及Button功能

3.寫一個Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class 往上移動腳本 : MonoBehaviour
{
    public GameObject player;

    public void BTNupup()
    {
        if (Input.GetMouseButton(0))
            player.transform.Translate(Vector3.up * Time.deltaTime, Space.Self);
    }

}

把這個腳本放入GameObject裡面

4.然後在Event Trigger裡面新增Add Event Type一個Update Selected動作,並把剛剛有腳本的GameObject拖曳進來

5.按壓那個區域便會發現指定的player物件會開始往上移動

全方位移動旋轉腳本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class 長壓按鈕總集 : MonoBehaviour
{   
    public GameObject player ; //要控制的目標1

    //1.首先用UI製作一個要被點選的區域(可以用圖片、Button等等)
    //2.Add Component 裡面選擇 Event Trigger以及Button功能
    //3.將以上腳本貼在空的Empty GameObject裡面
    //4.在Event Trigger裡面新增Add Event Type一個 Update Selected動作,並把步驟3有腳本的GameObject拖曳進來

    // Start is called before the first frame update
    void Start()
    {  }

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

    public void 往上()
    {
        if (Input.GetMouseButton(0))
            player.transform.Translate(Vector3.up * Time.deltaTime, Space.Self);
    }

    public void 往下()
    {
        if (Input.GetMouseButton(0))
            player.transform.Translate(Vector3.down * Time.deltaTime, Space.Self);
    }

    public void 往左()
    {
        if (Input.GetMouseButton(0))
            player.transform.Translate(Vector3.left * Time.deltaTime, Space.Self);
    }

    public void 往右()
    {
        if (Input.GetMouseButton(0))
            player.transform.Translate(Vector3.right * Time.deltaTime, Space.Self);
    }

    public void 往前()
    {
        if (Input.GetMouseButton(0))
            player.transform.Translate(Vector3.forward * Time.deltaTime, Space.Self);
    }

    public void 往後()
    {
        if (Input.GetMouseButton(0))
            player.transform.Translate(Vector3.back * Time.deltaTime, Space.Self);
    }

    public void 上轉()
    {
        if (Input.GetMouseButton(0))
            player.transform.Rotate(-Time.deltaTime,0,0);
    }

    public void 下轉()
    {
        if (Input.GetMouseButton(0))
            player.transform.Rotate(Time.deltaTime,0,0);
    }

    public void 左轉()
    {
        if (Input.GetMouseButton(0))
            player.transform.Rotate(0,-Time.deltaTime,0);
    }

    public void 右轉()
    {
        if (Input.GetMouseButton(0))
            player.transform.Rotate(0,Time.deltaTime,0);
    }



    
}



回應