目前我的角色在键盘上完美运行,但是当我通过 3 个 UI 按钮将你的动作转换为触摸时(我也尝试过 UI 图像,但成功了),我没有成功
它基本上是向右、向左、跳跃。
应该如何做才能使其遵循以下说明:
当用户按下方向键时,角色不会停止行走,直到用户释放按钮,而当按下跳跃键时,玩家会跳跃。
这是我用来通过键盘移动的脚本!
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
public float velocity;
public Transform player;
private Animator animator;
public bool isGrounded;
public float force;
public float jumpTime = 0.4f;
public float jumpDelay = 0.4f;
public bool jumped = false;
public Transform ground;
private Gerenciador gerenciador;
// Use this for initialization
void Start ()
{
gerenciador = FindObjectOfType (typeof(Gerenciador)) as Gerenciador;
animator = player.GetComponent<Animator> ();
gerenciador.StartGame ();
}
// Update is called once per frame
void Update ()
{
Move ();
}
void Move ()
{
isGrounded = Physics2D.Linecast (this.transform.position, ground.position, 1 << LayerMask.NameToLayer ("Floor"));
animator.SetFloat ("run", Mathf.Abs (Input.GetAxis ("Horizontal")));
if (Input.GetAxisRaw ("Horizontal") > 0) {
transform.Translate (Vector2.right * velocity * Time.deltaTime);
transform.eulerAngles = new Vector2 (0, 0);
}
if (Input.GetAxisRaw ("Horizontal") < 0) {
transform.Translate (Vector2.right * velocity * Time.deltaTime);
transform.eulerAngles = new Vector2 (0, 180);
}
if (Input.GetButtonDown ("Vertical") && isGrounded && !jumped) {
// rigidbody2D.AddForce (transform.up * force);
GetComponent<Rigidbody2D> ().AddForce (transform.up * force);
jumpTime = jumpDelay;
animator.SetTrigger ("jump");
jumped = true;
}
jumpTime -= Time.deltaTime;
if (jumpTime <= 0 && isGrounded && jumped) {
animator.SetTrigger ("ground");
jumped = false;
}
}
}
C# 如果可能的话,请记住我对这些按钮使用 Canvas UI =]
对于跳跃动作,您需要一个按钮。游戏对象->UI->按钮。将图像替换为您自己的图像,然后单击“设置原始大小”。将按钮的大小重新调整为适合您的游戏的大小。
将按钮附加到跳跃按钮下面的插槽脚本。
public Button jumpButton;
void jumpButtonCallBack()
{
// rigidbody2D.AddForce (transform.up * force);
GetComponent<Rigidbody2D>().AddForce(transform.up * force);
jumpTime = jumpDelay;
animator.SetTrigger("jump");
jumped = true;
}
void OnEnable(){
//Un-Register Button
jumpButton.onClick.AddListener(() => jumpButtonCallBack());
}
void OnDisable(){
//Un-register Button
jumpButton.onClick.RemoveAllListeners();
}
For the Left and Right移动按钮,你应该not use Button
他们的组件就像跳跃按钮。你必须实施虚拟操纵杆使其看起来更真实。 Unity 有一个名为 CrossPlatformInputManager 的资源可以做到这一点。您必须导入它并对其进行一些修改才能使用它。手表this https://www.youtube.com/watch?v=nGYObojmkO4了解如何导入它。
现在,您可以更换您的Input.GetAxis
and Input.GetAxisRaw
函数与CrossPlatformInputManager.GetAxis("Horizontal")
and CrossPlatformInputManager.GetAxisRaw("Horizontal")
.
如果您让它工作,那么可以使用下面的方法使您的代码与移动设备和桌面设备兼容。
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBGL
//put your Input.GetAxis` and `Input.GetAxisRaw` code here
#elif UNITY_ANDROID || UNITY_IOS
//Put your `CrossPlatformInputManager.GetAxis("Horizontal")` and `CrossPlatformInputManager.GetAxisRaw("Horizontal")`. here
#endif
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)