我正在嘗試制作一種基于動量的平臺游戲,您不能像手機游戲一樣改變方向或在空中移動,
我在 C# 方面不是最好的,如果這是一個愚蠢的問題,請原諒我,
我正在使用畫布上的按鈕作為輸入,只要按住按鈕,我希望我的播放器繼續移動,但我似乎必須繼續點擊才能讓播放器移動
enter code here using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController : MonoBehaviour
{
private float moveSpeed;
private float jumpSpeed;
public bool onGround = true;
private Rigidbody2D playerRb;
// Start is called before the first frame update
void Start()
{
moveSpeed = 100;
jumpSpeed = 3;
playerRb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
}
void onCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Level")
{
onGround = true;
}
}
public void MoveLeft()
{
if (onGround)
{
playerRb.AddForce(new Vector2(-moveSpeed, 0), ForceMode2D.Force);
}
}
public void MoveRight()
{
if (onGround)
{
playerRb.AddForce(new Vector2(moveSpeed, 0), ForceMode2D.Force);
}
}
}
如您所見,我為我的按鈕創建了 2 個不同的功能,以便在單擊它們時激活它們
無論如何我可以做到,只要按下按鈕,這些功能就會繼續運行?
uj5u.com熱心網友回復:
當你按下按鈕時,你需要設定剛體的速度,當你抬起手指時,將速度設定為零。這是一個非常簡單的實作。例如,我還建議檢查它是如何在 CorgiEngine 中完成的。
uj5u.com熱心網友回復:
您將需要一些可以實際執行此操作的自定義按鈕。
例如像
[RequireComponent(typeof (Button))]
public class ContinuousButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler, IPointerUpHandler
{
[SerializeField] private Button button;
private Coroutine coroutine;
private void Awake ()
{
Reset();
}
private void OnValidate()
{
Reset();
}
private void Reset ()
{
if(!button) button = GetComponent<Button>();
}
private void OnPointerEnter(PointerEventData pointerEventData)
{
// Not really doing anything but required for OnPointerExit to work
}
private void OnPointerExit(PointerEventData pointerEventData)
{
if(coroutine == null) return;
// cancel the routine if pointer leaves button
StopCoroutine (coroutine);
}
public void OnPointerDown(PointerEventData pointerEventData)
{
// optionally only take left mouse button and ignore the rest
if(pointerEventData.button != PointerEventData.InputButton.Left) return;
// Start a new continuous routine which will simulate a click each frame
coroutine = StartCoroutine(WhilePressed(pointerEventData));
}
private void OnPointerUp(PointerEventData pointerEventData)
{
if(coroutine == null) return;
// cancel the routine when letting go of the button
StopCoroutine(coroutine);
}
private IEnumerator WhilePressed (PointerEventData eventData)
{
// This is fine in a Coroutine as long as you yield inside
while(true)
{
button.OnPointerClick(eventData);
// Tells Unity to "pause" the execution here
// render this frame and continue from here
// in the next frame
yield return null;
}
}
}
只需將它附加到與組件相同GameObject的Button位置,它就會將其轉換為一個連續(按住)按鈕,基本上onClick每幀都會呼叫偵聽器。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/508675.html
標籤:C#unity3d
