目前我的角色在键盘上完美运行,但是当我将你的动作转换为触摸时,通过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来实现这些按钮=]
答案 0 :(得分:2)
对于Jump动作,你需要的是一个Button。的 GameObject-&GT; UI-&GT;按钮即可。用您自己的图像替换图像,然后单击&#34;设置原始大小&#34;。将按钮重新调整为适合您游戏的大小。
将按钮附加到下面的跳转按钮插槽脚本。
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();
}
对于左和右移动按钮,您应该不使用Button
组件,例如跳转按钮。您必须实施 Virtual JoyStick 才能使其看起来更逼真。 Unity拥有名为CrossPlatformInputManager的资产,可以做到这一点。你必须导入它并稍微修改它才能使用它。观看this以了解如何导入它。
现在,您可以将Input.GetAxis
和Input.GetAxisRaw
功能替换为CrossPlatformInputManager.GetAxis("Horizontal")
和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
答案 1 :(得分:0)
我认为您应该使用EventTrigger OnPointerDown和OnPointerUp事件:
http://docs.unity3d.com/ScriptReference/EventSystems.EventTrigger.html
我希望它可以帮到你