C# 使用UI按钮而不是键盘按钮调用函数
在我的2D Unity游戏中我可以用箭头键和空格键控制我的角色。因为我希望它可以在android手机上播放,所以我想改用UI按钮 我已经创建了3个UI按钮:C# 使用UI按钮而不是键盘按钮调用函数,c#,unity3d,C#,Unity3d,在我的2D Unity游戏中我可以用箭头键和空格键控制我的角色。因为我希望它可以在android手机上播放,所以我想改用UI按钮 我已经创建了3个UI按钮: 向右移动 向左移动 跳跃 我想这样做,这三个按钮将能够做同样的工作,作为键做的代码,我现在 这是我的Move2D脚本: 使用系统集合; 使用System.Collections.Generic; 使用UnityEngine; 公共类:单一行为 { 公共浮子移动速度=5f; 公共bool isGrounded=false; [Serial
- 向右移动
- 向左移动
- 跳跃
使用系统集合;
使用System.Collections.Generic;
使用UnityEngine;
公共类:单一行为
{
公共浮子移动速度=5f;
公共bool isGrounded=false;
[SerializeField]私有刚体2d刚体;
//每帧调用一次更新
无效更新()
{
跳跃();
Vector3移动=新的Vector3(Input.GetAxis(“水平”),0f,0f;
transform.position+=移动*时间.延迟*移动速度;
}
私人空间
{
如果(!rigidbody)rigidbody=GetComponent();
}
公共跳转
{
if(isground&&Input.GetButtonDown(“跳转”))
{
刚体.附加力(新矢量3(0f,5f),力模2D.脉冲);
}
}
}
注意:(在此脚本中,有一些函数调用另一个名为Grounded的函数,用于检查角色是否接触地板)
-
非常感谢您提供的任何信息或建议。假设您已经阅读了文档,并且知道如何引用和配置UI。按钮通常(否则请观看)您可以这样做
public class Move2D : MonoBehaviour
{
public float moveSpeed = 5f;
public bool isGrounded = false;
[SerializeField] private Rigidbody2D rigidbody;
private void Awake()
{
if (!rigidbody) rigidbody = GetComponent<Rigidbody2D>();
}
// this one you simply reference to a normal button
// or you could also use a continues button to auto jump see below
public void Jump()
{
if (isGrounded)
{
rigidbody.AddForce(new Vector3(0f, 5f), ForceMode2D.Impulse);
}
}
private float movement;
// this you reference on the left and right button
public void Move(float value)
{
movement = value;
}
// AND AGAIN
// you should always use MovePosition for RIGIDBODIES as I already told you last time
private void FixedUpdate()
{
rigidbody.MovePosition(rigidbody.position + Vector2.right * movement * Time.deltaTime * moveSpeed);
}
}
将其放在左右按钮上,并参考Move
方法。到一个按钮,例如通过检查器将-1
传递到另一个按钮1
有关IPointerXYHandler
的更多信息,请参见
注意:在智能手机上输入,所以不必担心,但我希望这个想法变得清晰起来sooo。。。到目前为止你试过什么<代码>跳转应该非常明显。。。对于
移动
,您需要一个带有简单浮点参数的方法,并在按钮中将其设置为1
或-1
。。。问题出在哪里?改装触摸控制装置不是件容易的事。对于大多数游戏来说,它根本不是一种好的输入方法。游戏必须为它而设计。通常你在设计时会考虑到最糟糕的输入法,然后将其扩展到可以使用更高级的输入法(如按键)的情况下。非常感谢。我如何使角色在按下按钮时保持移动?
public class ContinuesButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler, IPointerUpHandler
{
[SerializeField] private Button button;
[SerializeField] private UnityEvent whilePressed;
private 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;
}
}
}