簡體   English   中英

在 Unity 中通過單擊鼠標移動

[英]Moving with Clicking mouse in Unity

我想在我的游戲中像 MOBA 類型一樣移動。 但我無法解決問題。 我的 object 每次單擊都會移動一次。 但是我想一鍵移動所有距離,如何釋放這個?

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

public class Hero : MonoBehaviour
{
    private Vector3 pos = new Vector3(10, 0, 10);
    public CharacterController controller;

    public float speed = 10f;

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

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 a = transform.position;
            Vector3 b = new Vector3(10, 0, 10);
            transform.position = Vector3.MoveTowards(a, b, speed);
        }
    }
}

當鼠標按鈕按下時,您的代碼將移動播放器。 您需要在按下鼠標按鈕時設置目標並將播放器移動到 if 語句之外。 這是你如何做到的

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

public class Hero : MonoBehaviour
{
    private Vector3 pos = new Vector3(10, 0, 10);
    Vector3 a;
    Vector3 b;
    public CharacterController controller;

    public float speed = 10f;

    // Start is called before the first frame update
    void Start()
    {
     b = transform.position;// initial value

    }

    // Update is called once per frame
    void Update()
    {
        a = transform.position;
        if (Input.GetMouseButtonDown(0))
        {
            b = pos;
            
        }
        transform.position = Vector3.MoveTowards(a, b, speed);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM