iT邦幫忙

2025 iThome 鐵人賽

0
自我挑戰組

從零開始做出我的第一款 Unity 遊戲系列 第 11

DAY11-讓角色動起來(2)

  • 分享至 

  • xImage
  •  

輸入完這串就代表我們已經處理好玩家的按鍵部分了
https://ithelp.ithome.com.tw/upload/images/20251020/20178853IIpTscDJfg.png

接下來我們要讓物件朝按鍵方向持續移動
我們開啟Snack腳本後,輸入以下程式碼:

using UnityEngine;

public class Snack : MonoBehaviour
{
    Vector3 direction;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        Debug.Log(transform.position);

        Time.timeScale = 0.1f;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
            Debug.Log("W");
            direction = Vector3.up;
        }
        if (Input.GetKeyDown(KeyCode.A))
        {
            Debug.Log("A");
            direction = Vector3.left;
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            Debug.Log("S");
            direction = Vector3.down;
        }

        if (Input.GetKeyDown(KeyCode.D))
        {
            Debug.Log("D");
            direction = Vector3.right;
        }


    }
    void FixedUpdate()
    {
        transform.Translate(direction);

    }
}

輸入完後按command+5,開啟unity即可讓物件朝按鍵方向持續移動了


上一篇
DAY10-讓角色動起來(1)
下一篇
DAY12-讓角色動起來(3)
系列文
從零開始做出我的第一款 Unity 遊戲21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言