【发布时间】:2019-09-15 04:45:38
【问题描述】:
我正在 Unity 中制作一个平台游戏,其中球通过三个按钮移动:
- 向右移动
- 向左移动
- 跳跃
我已经拥有了现在可以使用的所有功能,但是要移动角色我需要继续发送一个按钮,而不是像我想要的那样按住它。我尝试了一些在教程中找到的方法,但由于我还是个初学者,我没能成功。
这是我的 Move2D 脚本附加到角色的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move2D : MonoBehaviour
{
public float moveSpeed = 5f;
public bool isGrounded = false;
[SerializeField] private Rigidbody2D rigidbody;
private void Awake()
{
if (!rigidbody) rigidbody = GetComponent<Rigidbody2D>();
}
public void Jump()
{
if (isGrounded)
{
rigidbody.AddForce(new Vector3(0f, 5f), ForceMode2D.Impulse);
}
}
public void Move(float value)
{
Vector3 movement = new Vector3(value, 0f, 0f);
transform.position += movement * Time.deltaTime * moveSpeed;
}
}
而这是第二个脚本,主要控制所有的运动:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ContinuesButton : MonoBehaviour, IPointerExitHandler, IPointerDownHandler, IPointerUpHandler
{
[SerializeField] private Button button;
[SerializeField] private UnityEvent whilePressed;
private readonly bool isHover;
private void Awake()
{
if (!button) button = GetComponent<Button>();
}
public void OnPointerDown(PointerEventData eventData)
{
StartCoroutine(WhilePressed());
}
public void OnPointerUp(PointerEventData eventData)
{
StopAllCoroutines();
}
public void OnPointerExit(PointerEventData eventData)
{
StopAllCoroutines();
}
private IEnumerator WhilePressed()
{
while (true)
{
whilePressed?.Invoke();
yield return null;
}
}
}
非常感谢任何信息或解释,因为这部分对我的游戏非常重要! :)
【问题讨论】: